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

标签 css alignment css-position center

如何将父容器垂直居中对齐到具有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/

相关文章:

css - Less 中基于颜色的条件逻辑

javascript - 如何在 Javascript PhoneGap 应用程序中居中对齐弹出窗口

javascript - 使用 css 对齐和填充

html - 如何使图像适合容器?

html - 在中心排列三个 DIV

css - IE定位div布局问题

html - CSS 中的定位问题

html - 使用 css 伪选择器的正确方法?

html - 图像大于视口(viewport)时不居中

css - css scale transform如何影响文档流?