admin 管理员组文章数量: 1087649
I'm trying to center a div with within its parent, vertically and horizontally.
JSFIDDLE: /
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);
I would love the answer, but I would also love to understand the logic behind it.
I'm trying to center a div with within its parent, vertically and horizontally.
JSFIDDLE: http://jsfiddle/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);
I would love the answer, but I would also love to understand the logic behind it.
Share Improve this question edited Apr 15, 2016 at 4:10 Aaron 7061 gold badge7 silver badges23 bronze badges asked Jun 28, 2013 at 16:22 user1469270user14692703 Answers
Reset to default 5Use jQuery' .css
function , like this:
child.css({
top: parent.height()/2 - child.height()/2 ,
left: parent.width()/2 - child.width()/2
}) ;
Not very elegant , but it works. The logic is to place the child in absolute
position relative to its parent contaner by defining its top
and left
properties.
Have a look : http://jsfiddle/pE5QT/9/
PS: CSS solution of course is more suitable here , but question' title is "Using jQuery to center a div within its parent" , so...
Try this code :
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");
Here is the working demo : http://jsfiddle/pE5QT/23/
You need to format your code because it's looking kinda... gross.
Anyway, this is how I'd do it. In your child CSS, you can do something like:
.child {
height: 100px;
width: 100px;
background-color:yellow;
margin-left: auto;
margin-right: auto;
}
And then for your vertical positioning:
child.css({'margin-top': (parent.height() - child.height()) / 2);
本文标签: javascriptUsing jQuery to center a div within its parentStack Overflow
版权声明:本文标题:javascript - Using jQuery to center a div within its parent - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744080385a2530130.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论