如何垂直对齐position:relative元素? [英] How do I vertically center align a position:relative element?
问题描述
如何将父容器垂直居中对齐具有 position:relative
的画布?父容器的子元素具有 position:absolute
。子元素位于父容器的中心。
How do I vertically center align the parent container to the canvas which has position:relative
? The parent container has a child element with position:absolute
. The child element has been positioned in the center of the parent container.
以下是代码段:
.container {
position: relative;
width: 300px;
height: 300px;
background-color: red;
margin: auto;
}
.item {
position: absolute;
width: 100px;
height: 100px;
background-color: blue;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
<div class="container">
<div class="item"></div>
</div>
推荐答案
一种解决方案是用两个包装器包装 .container
。给出第一个 display:table;
和 height:100%;宽度:100%;
和第二个显示:表格单元格;
和 vertical-align:居中;
。另外,请确保您的正文
和 html
具有完整的高度。
One solution is to wrap your .container
with two wrappers; give the first one display: table;
and height: 100%; width: 100%;
and the second display: table-cell;
and vertical-align: middle;
. Also make sure your body
and html
have full height.
这是一个工作示例:小链接。
另一个方法是将 top:50%;
应用于您的 .container
和 margin-top: -150px;
( 300px / 2 = 150px
)。 (请注意,此方法要求您知道容器的确切高度,因此可能可能不是您想要的确切高度,但也可能是!)。后一种方法的一些工作示例:另一个小链接。
Another method is to apply top: 50%;
to your .container
and margin-top: -150px;
(300px / 2 = 150px
). (Note that this method requires you to know the exact height of your container, so it might not be exactly what you want, but it might as well be!). A little working demo of this latter method: another little link.
希望对您有所帮助!
这篇关于如何垂直对齐position:relative元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!