hot_barbara hot_barbara - 2 months ago 6
CSS Question

dynamically resize div with text from center using CSS

Here's my original div with text in it (the blue line is a fixed position guide for reference):Original

When text is added to it, it looks like:

Current

However I'm looking for a CSS solution to make it look like this automatically when text is added to it:

Desired

I've tried

transform-origin
but that changes the origin point of the element for transform properties only. I know this could be done with JS but I'm looking for a CSS solution if it's out there. Thanks!

Answer

You could do like this

.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>

Update based on a comment and a codepen sample, where a container grows with its content

.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>