gpt4 book ai didi

javascript - 将javascript垂直居中应用于多个div

转载 作者:行者123 更新时间:2023-12-02 18:16:57 27 4
gpt4 key购买 nike

经过几个小时的尝试自己解决这个问题后,我觉得有必要向比我更了解的人求助。我有一个将子 div 置于父 div 中的函数。这一切都有效,唯一的问题是子 div 的大小发生变化,所以我需要一种方法将此函数单独应用于每个 div。

这是我的代码

HTML

<div class="outer">
<div class="inner">short text in here</div>
</div>

<div class="outer">
<div class="inner">some text in here more text here that is longer. This is longer</div>
</div>

CSS

.outer{background:#eee;height:150px;width:150px;margin-bottom:20px;}
.inner{width:130px;padding:10px;text-align:center;}

JavaScript

$(document).ready(function(){
var inner = $('.inner'),
ht = inner.height();

inner.css({'position':'absolute','top':'50%','margin':-ht/2+'px 0 0 0'});
});

http://jsfiddle.net/AMNVY/

最佳答案

Does this work for you?

我所做的只是编辑 css:

.outer{
background:#eee;
height:150px;
width:150px;
margin-bottom:20px;
display: table;
}
.inner{
width:130px;
padding:10px;
text-align: center;
vertical-align: middle;
display: table-cell;

}

不需要js...

关于javascript - 将javascript垂直居中应用于多个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19194991/

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