How to provide default font height or content when <p> or <span> has no characters?

。_饼干妹妹 提交于 2019-12-07 09:08:28

Question 2

The width behavior of p versus span is due to the CSS specification for the width property.

width does not apply to non-replaced inline elements (span), so p being a block level elements, takes on the width value.

Note that, if you apply display: inline-block to a span, then the width is recognized since an inline-block is not a non-replaced inline element.

Reference: http://www.w3.org/TR/CSS21/visudet.html#the-width-property

Question 3

HTML provides two generic, vanilla-flavored elements, div which is a block-level element, and span which is an inline element. span can be used within any element, be it p, li, td, i and so on. If you want a span nested in a p to have a particular styling, you can define a specific CSS rule to enable the styling that you need. If you want p like behavior with respect to width, padding, and margins, then you can specify display: inline-block. The HTML specification does not specify a generic inline-block element, probably because no member of the specification group saw a need for it.

Keep in mind that the default styling of HTML elements is browser dependent, so in theory, a browser's default style sheet could have a rule for p span, but as far as I know, such an implementation does not exist.

Question 1

To prevent an empty p tag from collapsing to zero height, I would use a :after pseudo-element to insert a non-breaking space (&nbsp; has the hex code 0xa0).

Note that since the span is an inline element, its height will not collapse to zero because the height of an inline, non-replaced element is determined by the line-height property (height is ignored), so you don't need to add the non-breaking space UNLESS you want an empty space to have non-zero width.

p, span {
  border: 1px dotted blue;
}
p:after, span:after {
  content: '\a0';
}
<h4>Empty p</h4>
<p></p>
<p>p tag with text.</p>

<h4>Empty span</h4>
<span></span>
<span>span tag with text.</span>

The solutions below provide a default height to a <p> without text and an attempt to simulate empty content in a <span>:

A

Using CSS, according to w3schools:

 p,span {height: 1em}

Will set the height:

Relative to the font-size of the element (2em means 2 times the size of the current font).

p, span {height: 1em}
<p></p>
<p>Above there's a ghost paragraph</p>
<span></span>
<span>To the left there's NO visible trace of a span</span>

B

Using only HTML, placing a space (&nbsp;) inside the <p> (so it actually does have a character):

<p>&nbsp;</p>
<p>Above there's a ghost paragraph with a space</p>
<span>&nbsp;</span>
<span>To the left there's a span with a space</span>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!