[英]Centering a div vertically using jquery
I know a lot of techniques out there for centering a div vertically, but I made this according to my thinking. 我知道有很多技巧可以使div垂直居中,但是我是根据自己的想法来做的。 I believe the concept is correct, but I'm not getting 100% results.
我相信这个概念是正确的,但是我没有得到100%的结果。
Here is the javascript 这是JavaScript
jQuery(document).ready(function(){
var l=jQuery('.div1').height();
var level=l/2;
var bt=jQuery('.div2').height()/2;
var val=level-bt;
jQuery('.div2').css("margin-top",val);
});
CSS CSS
.div1
{
height:50px;
background-color: red;
position:relative;
}
.div2
{
border: 1px solid;
background-color: orchid;
text-decoration: none;
letter-spacing: 1px;
text-transform:uppercase;
padding: 5px;
position: absolute;
right:5%;
top:0%
}
HTML HTML
<div class="div1"><div class="div2">vertical</div>
div2
div2
div2
height with half of div1
height by the result, if I give that as a margin-top, I should be able to get it to center vertically. div2
高度的一半减为div1
高度的一半,如果我将其作为页边距顶部,则应该能够使其垂直居中。 Am I right? Use outerHeight
to ignore the padding. 使用
outerHeight
忽略填充。
jQuery(document).ready(function () {
var l = jQuery('.div1').outerHeight();
var level = l / 2;
var bt = jQuery('.div2').outerHeight() / 2;
var val = level - bt;
jQuery('.div2').css("margin-top", val);
});
You're not taking into account the padding on div2, if you get the outerHeight
you should have more joy: http://jsfiddle.net/CPrtZ/1/ 您无需考虑div2上的填充,如果您获得了
outerHeight
您应该会更加高兴: http : //jsfiddle.net/CPrtZ/1/
jQuery(document).ready(function(){
var l=jQuery('.div1').height()/2;
var bt=jQuery('.div2').outerHeight()/2;
var val=l-bt;
jQuery('.div2').css("margin-top",val);
});
I realise that this question is about how to do center a div
vertically using jQuery, but it seems from the comments on this question that there is a mistaken belief that this cannot be done using only CSS. 我意识到这个问题是关于如何使用jQuery在
div
垂直居中,但是从对该问题的评论看来,似乎有一个错误的信念,即仅使用CSS不能做到这一点。 Here's a jsFiddle showing that it can be done. 这是一个jsFiddle,表明它可以完成。 It works in all current browsers and IE8+ .
它适用于所有当前的浏览器和IE8 + 。
HTML HTML
<div class="div1">
<div class="div2">vertically aligned while
<br />height is not fixed but
<br />based on content height</div>
</div>
CSS CSS
body {
display: table;
width: 100%;
}
.div1 {
height:200px;
background-color: red;
position:relative;
display: table-cell;
vertical-align: middle;
}
.div2 {
border: 1px solid;
background-color: orchid;
text-decoration: none;
letter-spacing: 1px;
text-transform:uppercase;
padding: 5px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.