最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using jQuery to center a div within its parent - Stack Overflow

programmeradmin6浏览0评论

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 user1469270user1469270
Add a ment  | 

3 Answers 3

Reset to default 5

Use 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);
发布评论

评论列表(0)

  1. 暂无评论