gpt4 book ai didi

css - 如何垂直居中对齐位置 :relative element?

转载 作者:技术小花猫 更新时间:2023-10-29 10:32:32 25 4
gpt4 key购买 nike

如何将父容器垂直居中对齐到具有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;。还要确保您的 bodyhtml 具有全高。

这是一个小的工作演示:little link .

另一种方法是将 top: 50%; 应用到你的 .containermargin-top: -150px; ( 300px/2 = 150px). (请注意,此方法要求您知道容器的确切高度,因此它可能不是您想要的,但也有可能!)。后一种方法的一些工作演示:another little link .

希望对您有所帮助!

关于css - 如何垂直居中对齐位置 :relative element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157992/

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