norkuy
norkuy

Reputation: 753

Block element background as opposed to child inline element background

Why do the descenders of the anonymous inline text inside the element stick out of the background or (content-area) of the element, while the element's background (or content-area) contains the descenders (and potential ascenders) of the text? Is this related to em-box calculations of the font, a block element not fully containing inline children, or maybe line-height 1 equal to font-size being an issue? https://jsfiddle.net/norkuy/462wzvq1/

p {
  font-size: 40px;
  margin: 0;
  line-height: 1;
  background: tomato;
  color: black;
  margin-top: 20px;
}

p span {
  background: DarkSlateGray;
  color: white;
}
<p>A sentence containing <span>ggg's</span> and <span>jjj's</span></p>

Upvotes: 3

Views: 163

Answers (1)

Brett DeWoody
Brett DeWoody

Reputation: 62841

The p elements, which are block elements, have their height calculated from the line-height of 1, which is calculated from the font-size of 40px. So the p has a calculated height of 40px, which isn't enough to cover the descenders.

The span elements, which are inline elements, have their height set automatically based on their content. They'll even ignore any height properties assigned to them. So the height, and background-color covers the required space.

As an additional example, I've copied the same snippet but applied a class to turn the span elements into inline-block elements, which will obey the height we've defined.

p {
  font-size: 40px;
  margin: 0;
  line-height: 1;
  background: tomato;
  color: black;
  margin-top: 20px;
}

p span {
  background: DarkSlateGray;
  color: white;
  
  /*
  /  No matter what we do
  /  we can't change the height
  */
  font-size: 40px;
  line-height: 1;
  height: 40px !important;
}

.turnedIntoBlock {
  display: inline-block;
}
<p>A sentence containing <span>ggg's</span> and <span>jjj's</span></p>

<p>A sentence containing <span class="turnedIntoBlock">ggg's</span> and <span class="turnedIntoBlock">jjj's</span></p>

Upvotes: 1

Related Questions