gpt4 book ai didi

javascript - 使用 jQuery 将 div 在其父级中居中

转载 作者:太空宇宙 更新时间:2023-11-04 15:13:56 25 4
gpt4 key购买 nike

我正在尝试使 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);

我很想知道答案,但我也很想了解它背后的逻辑。

最佳答案

使用 jQuery 的 .css 函数,像这样:

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

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

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

PS:CSS 解决方案当然更适合这里,但是问题的标题是“使用 jQuery 将 div 在其父级中居中”,所以...

关于javascript - 使用 jQuery 将 div 在其父级中居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17369328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com