CSS 如何垂直居中对齐位置:相对元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12157992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I vertically center align a position:relative element?
提问by Vennsoh
How do I vertically center align the parent containerto 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.
如何将父容器垂直居中对齐到具有 的画布 position:relative?父容器有一个带有 的子元素position:absolute。子元素已定位在父容器的中心。
Here's a snippet:
这是一个片段:
.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>
回答by Chris
One solution is to wrap your .containerwith 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 bodyand htmlhave full height.
一种解决方案是.container用两个包装器包装您;给出第一个display: table;和height: 100%; width: 100%;第二个display: table-cell;和vertical-align: middle;。还要确保你的body和html有全高。
Here's a little working demo: little link.
这是一个小的工作演示:little link。
Another method is to apply top: 50%;to your .containerand margin-top: -150px;(300px / 2 = 150px). (Note that this method requires you to know the exact height of your container, so it mightnot be exactly what you want, but it might as well be!). A little working demo of this latter method: another little link.
另一种方法是适用top: 50%;于您的.container和margin-top: -150px;( 300px / 2 = 150px)。(请注意,此方法要求您知道容器的确切高度,因此它可能不是您想要的,但也可能是!)。后一种方法的一个小工作演示:另一个小链接。
I hope that helped!
我希望有帮助!

