htmlcsscenteringline-height

Center with line-height without height


As you know, we can use the line-height property with a value that is equal to the height property of a container to vertically center a single line within that container:

.container {
  width: 300px;
  height: 200px;
  line-height: 200px;
  text-align: center;
  outline: 1px solid red;
}
<div class="container">
  <p>This is some text.</p>
</div>

I have seen this method in many references, for example:

Now the question is, why is the height property set? Is it necessary, or can we simply manage with line-height only?


Solution

  • If a single-text is present, your line-height will be enough to vertically-center the text. It is because, since even 1 single line is present, equalling it out to 200px, will automatically set min-height to 200px.

    .container {
      width: 300px;
      line-height: 200px;
      text-align: center;
      outline: 1px solid red;
    }
    <div class="container">
      <p>This is some text.</p>
    </div>

    Now, lets see with example where there is no-text.

    Here, in this case, your line-height did not work, as there is no-text present. In this scenario, your height:200px would have come handy, as still there is no-text, it would have atleast provided 200px height even without any content (so here, if you want some height to always being present, even without any data, height:200px would be useful).

    .container {
      width: 300px;
      line-height: 200px;
      text-align: center;
      outline: 1px solid red;
    }
    <div class="container">
      <p></p>
    </div>