当使用 jQuery 垂直对齐 div 中的文本时,整个 div 都会移动。文本与其他 div 垂直对齐,但仍与它所在的 div 顶部对齐。我怎样才能阻止它这样做?
这是一个 jsfiddle:http://jsfiddle.net/gvwzdjas/
遗憾的是, fiddle 并没有准确显示正在发生的事情。我不确定用另一种方式来展示它...
这是我正在使用的 HTML。
<div class="grid grid-pad">
<div class="col-1-3">
<div class="content">
<h3>
TEXT HERE
</h3>
</div>
</div>
<div class="col-1-3">
<div class="content">
<h3>
TEXT HERE
</h3>
</div>
</div>
<div class="col-1-3">
<div class="content">
<h3>
TEXT HERE
</h3>
</div>
</div>
</div>
这是我正在使用的 jQuery。
<script>
(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
return this.each(function(i){
var ah = $(this).height();
var ph = $(this).parent().height();
var mh = Math.ceil((ph-ah) / 2);
$(this).css('margin-top', mh);
});
};
})(jQuery);
$('#item').vAlign();
</script>
这是我正在使用的 CSS
*, *:after, *:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
[class*='col-'] {
float: left;
padding-right: 20px; /* column-space */
}
.grid {
width: 100%;
max-width: 1140px;
min-width: 755px;
margin: 0 auto;
overflow: hidden;
}
.grid:after {
content: "";
display: table;
clear: both;
}
.grid-pad {
padding-top: 10px;
padding-left: 20px; /* grid-space to left */
padding-right: 0px; /* grid-space to right: (grid-space-left - column-space) e.g. 20px-20px=0 */
}
.col-1-3, .col-4-12 {
width: 33.33%;
}
.content {
height:250px;
background-color:#fff;
text-align:center;
}
最佳答案
$('#item').vAlign();
您的 html 中没有 #item
尝试
h3{
position: relative;
}
和
(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function () {
return this.each(function (i) {
var ah = $(this).height();
var ph = $(this).parent().height();
var mh = Math.ceil((ph - ah) / 2);
$(this).css('top', mh);
});
};
})(jQuery);
$('h3').vAlign();
看看jsfiddle
关于jQuery vertical align middle 移动整个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196190/