垂直居中绝对 div,没有定义的高度



我正在尝试将absolute位置的div 垂直居中relative位置div。问题是我的父div 有一个不断扩大的height.今天可能是300,明天可能是100。因此,无法定义高度,但子div 必须垂直居中。

这是我尝试过的:

.parrent{
  position: relative;
}
.child {
  background: red;
  width: 50px;
  height: 50px;
  
  position: absolute;
  top: 0;
  bottom: 0;
}
<div class="parrent">
  <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
  
  <div class="child">
  
  </div>
</div>

由于我需要尽快工作,因此我对任何解决方案都持开放态度。

你可以

.child放在top: 50%;处,然后用transform: translateY(-50%);向上移动它,这将把你的元素居中。这会将您的元素从父元素的顶部移开 50%,并将其向上移动子元素高度的 50%。

.parrent{
  position: relative;
}
.child {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

请参阅此小提琴的工作解决方案

您可以使用

以下代码段:

https://jsfiddle.net/ocbzdkpd/1/

基本上你需要:

  top: 50%;
  transform:translateY(-50%);

因为盒子的大小无关紧要。

Flexbox可以在这里为您提供帮助。

.parent{
  display:flex;
  align-items:center;     // vertical alignment
}
.child {
  background: red;
  width: 50px;
  height: 50px;   
  position: absolute;
}
<div class="parent">
  <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>   
  <div class="child"></div>
</div>

最新更新