Home > other >  How to set an empty paragraph element to the minimum height of the font-size (text)
How to set an empty paragraph element to the minimum height of the font-size (text)

Time:06-01

How to set an empty paragraph element <p> to the height of the font size?

If a paragraph element is empty it has no height. How to set the minimum height to the text height (font-size)?

I know you can add &nbsp; to the element, but I want to set it purely by CSS

CodePudding user response:

You can use a whitespace in a pseudo-element. This should work:

p::after {
  content: '\00a0 '
}

Live demo here: https://jsfiddle.net/o96swntm/

CodePudding user response:

Try to use

p:empty {
    height: 14px;
}

CodePudding user response:

You can assign the regular p min-height in a css var.

:root {
  --p-height: 20px;
}

p {  
  color: white;
  background: green;
  min-height:var(--p-height);
}
<p></p>
<p>lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem lorem </p>

CodePudding user response:

You can use the pseudo class :empty if the paragraph element has not child elements such as anchor links or spans, or you can create a pseudo ::before or ::after element with an empty space character \00a0 in the content property.

If it's a visual match you are looking you for, for instance have a matching x-height of the font to an empty element that may have a different coloured background you'll need to manually measure the height of the <p> element in the dev tools by hovering over the element with the element selector when it has some text in and set it to that height value so as to factor in different fonts render at different sizes even when using the same font-size value due to varying font characterstics (although there is CSS coming in the pipeline to address this with properties such as line-height-trim which you can look at here: line-height-trim)

  • Related