使用jQuery将div放在其父级中心

时间:2013-06-28 16:22:45

标签: javascript jquery html centering

我正在尝试将div放在其父级内,纵向和横向。

JSFIDDLE:http://jsfiddle.net/pE5QT/

CSS:

.parent {
    width: 200px;
    height: 200px; 
    background-color:red;
}

.child {
    height: 100px;
    width: 100px;
    background-color:yellow;
}

HTML:

<div class="parent"> b
    <div class="child"> a </div>
</div>

使用Javascript:

var parent = $('.parent');
var parentDimensions = parent.height() * parent.width();

var child = $('.child');
var childDimensions = child.height() * child.width();

parent.html();
child.html(childDimensions);

我很喜欢这个答案,但我也很想理解它背后的逻辑。

3 个答案:

答案 0 :(得分:5)

使用jQuery'.css函数,如下所示:

 child.css({
   top: parent.height()/2 - child.height()/2 ,
   left: parent.width()/2 - child.width()/2
 }) ;

不是很优雅,但它有效。其逻辑是通过定义其absolutetop属性,将孩子置于相对于其父容器的left位置。

看看:http://jsfiddle.net/pE5QT/9/

PS:当然CSS解决方案更合适,但是问题'标题是'使用jQuery将div放在其父中“,所以......

答案 1 :(得分:0)

您需要格式化代码,因为它看起来有点......粗略。

无论如何,我就是这样做的。在您的孩子CSS中,您可以执行以下操作:

.child {
   height: 100px;
   width: 100px;
   background-color:yellow;

   margin-left: auto;
   margin-right: auto;
}

然后进行垂直定位:

child.css({'margin-top': (parent.height() - child.height()) / 2);

答案 2 :(得分:0)

试试这段代码:

var parent = $('.parent');
var child = $('.child');

child.css("position","absolute");
child.css("top", ((parent.height() - child.outerHeight()) / 2) + parent.scrollTop() + "px");
child.css("left", ((parent.width() - child.outerWidth()) / 2) + parent.scrollLeft() + "px");

以下是工作演示:http://jsfiddle.net/pE5QT/23/

相关问题