Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make empty div of one line height

Tags:

css

Is it possible to create a rule that will make the following HTML:

<div style="width: 100%"></div>

of one line height using just CSS, or do I need to put &nbsp; as the content?

like image 975
jcubic Avatar asked Oct 13 '13 17:10

jcubic


People also ask

How do you create an empty div height?

Approach: The solution is to give some height (or min-height) and width (or min-width) to your HTML div. When you set a particular height and width for a div, it does not matter if it is empty or overflowed, it will only take up the space as given in the code.

What is the difference between line height 20px and 2?

What is the difference between the following line-height settings? line-height: 20px; line-height: 2; The value of 20px will set the line-height to 20px. The value of 2 will set the line-height to twice the size of the corresponding font-size value.


2 Answers

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.

like image 54
Oriol Avatar answered Oct 04 '22 06:10

Oriol


Just another solution:

.your-selector:empty::after {
    content: ".";
    visibility: hidden;
}
like image 22
vothaison Avatar answered Oct 04 '22 07:10

vothaison