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
as the content?
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 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.
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 (​
)
div { border: 1px solid red; }
<div></div><!-- There is a zero-width space inside -->
As you say,
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With