使用CSS使用来自中心的文本动态调整div

时间:2016-09-21 18:04:19

标签: html css

这是我的原始div,其中包含文字(蓝线是固定位置指南供参考):Original

当文本添加到它时,它看起来像:

Current

然而,我正在寻找一种CSS解决方案,以便在文本添加到它时自动显示:

Desired

我尝试了transform-origin,但只更改了转换属性元素的原点。我知道这可以用JS完成,但我正在寻找一个CSS解决方案,如果它在那里。谢谢!

1 个答案:

答案 0 :(得分:2)

你可以这样做

.center {
  margin-top: 100px;
  background: lightblue;
  height: 5px;
}

.text {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<div class="center">
  <div class="text">
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
    Hey there ...<br>
</div>
</div>

根据评论和codepen示例进行更新,其中容器随其内容增长

.container{
  border: 1px solid red;  
}
.center {
  border-top: 2px solid lightblue;
  position: relative;
  top: -50%;
  transform: translateY(50%);
}
.text {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<div class="container">
  <div class="center">
    <div class="text">
      Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>Hey there ...
      <br>
    </div>
  </div>
</div>