我想在一个较大的 div 内垂直对齐一个 div。我该怎么做?
HTML:
<div class="outer">
<div class="middle">
<h1>test</h1>
<h2>Test</h2>
</div>
</div>
CSS:
.middle {height:160px;display: table-cell; vertical-align: middle;text-align:center;background:red}
.outer {height:550px;background:#eee}
最佳答案
您可以使用一种相当简单的技术来利用 css 转换,如下所示:
HTML
<div class="outer">
<div class="middle">
<h1>Test</h1>
<h2>Test</h2>
</div>
</div>
CSS
.middle {
margin: auto;
position: absolute;
top: 50%;
-webkit-transform: translate(0, -50%);
transform: translate(0, -50%);
background-color: #ccc;
}
.outer {
height:550px;
width:100%;
background-color:#eee;
position: relative;
}
你更新的 fiddle here .
您还可以通过添加 left: 50%
属性并更改 transform: translate(0, -50%);
行来使元素垂直和水平居中转换:translate(-50%, -50%);
。
垂直和水平居中here
关于html - 垂直对齐div内的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28264031/