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

时间:2018-01-26 15:06:25

标签: html css css3

我正试图将absolute位置relative位于height位置div内的div垂直居中。问题是我的父div有一个不断扩大的.parrent{ position: relative; } .child { background: red; width: 50px; height: 50px; position: absolute; top: 0; bottom: 0; }。今天它可能是300,明天是100.所以定义高度是不可能的,但是子div必须垂直居中。

以下是我的尝试:



<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>
&#13;
data = { 
  "key1": ["value1", value2", "value3"],
  "key2": ["value4", "value5", "value6"],
  "key2": ["value7"]
}
&#13;
&#13;
&#13;

由于我需要尽快开展工作,我可以接受任何解决方案。

3 个答案:

答案 0 :(得分:4)

您可以将.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%);
}

See working solution on this fiddle

答案 1 :(得分:2)

您可以使用此代码段:

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

基本上你需要:

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

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

答案 2 :(得分:1)

Flexbox 可以为您提供帮助。

&#13;
&#13;
.parent{
  display:flex;
  align-items:center;     // vertical alignment
}

.child {
  background: red;
  width: 50px;
  height: 50px;   
  position: absolute;
}
&#13;
<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>
&#13;
&#13;
&#13;