如何将父容器垂直居中对齐到具有position:relative
的 Canvas ?父容器有一个带有 position:absolute
的子元素。子元素已经定位在父容器的中心。
这是一个片段:
.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%; width: 100%;
和第二个 display: table-cell;
和 vertical-align: middle;
。还要确保您的 body
和 html
具有全高。
这是一个小的工作演示:little link .
另一种方法是将 top: 50%;
应用到你的 .container
和 margin-top: -150px;
( 300px/2 = 150px
). (请注意,此方法要求您知道容器的确切高度,因此它可能不是您想要的,但也有可能!)。后一种方法的一些工作演示:another little link .
希望对您有所帮助!
关于css - 如何垂直居中对齐位置 :relative element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157992/