Make empty div of one line height

Some possibilities:

  • Set height (or min-height) to the line-height's used value.

    The initial value of line-height is normal, whose used value is implementation-dependent, but the spec suggests a number between 1.0 and 1.2

    In my case (FF27 for winXP with font-family: "times new roman") that value is 1.25, so you could use height: 1.25em. However, that value might be different with other fonts or implementations.

    Then, it's better to manually set line-height to some value, like line-height: 1.25em.

    div {
      border: 1px solid red;
      min-height: 1.25em;
      line-height: 1.25;
    }
    <div></div>

    Note that if you want to set those styles to the elements only when it has no content, you can use the :empty pseudo-class:

    div:empty {
      border: 1px solid red;
      height: 1.25em;
      line-height: 1.25;
    }
    <div></div>

  • Inserting some content to the element.

    For example, you can add a normal space and set white-space to pre-wrap (or pre) to prevent the space from collapsing:

    div {
      border: 1px solid red;
      white-space: pre-wrap;
    }
    <div> </div>

    Alternatively, you can use a zero-width space (&#8203;)

    div { border: 1px solid red; }
    <div>​</div><!-- There is a zero-width space inside -->

    As you say, &nbsp; would also work. However, it is a non-breaking space, so its purpose is preventing automatic line breaks. Then, using it would be semantically incorrect IMO.

    And as @BoltClock says, those whitespaces could be inserted with CSS pseudo-elements, but note that might not work on very old browsers.


Just another solution:

.your-selector:empty::after {
    content: ".";
    visibility: hidden;
}

Tags:

Css