no Text baseline alig...">

Vertical-align: base outer element weird height

here is the html code below:

<div class="container">
   no Text
   <span class="base">baseline align</span>
</div>

      

Css code:

div {
    font-size: 20px;
    line-height: 100px;
    outline: 1px solid red;
}
span {
    font-size: 40px;
    display: inline-block;
    background: wheat;
}

      

my question is why the height of the container element is 107px and not 110px.

containerHeight = lineHeight + (spanFont - divFont)/2 = 100px + 10px = 110px

      

+3


source to share


1 answer


Consider the code snippet reproduced below and look at the yellow, right element that has font-size: 50px

and line-height: 36px

. Note that although the font size is 50 pixels, the vertical space occupied by the character (glyph) is less than 50 pixels, more than 36 pixels. Fonts are designed so that there is a field in which characters are stored, and glyphs / characters are located inside that field.

The computed total window height is the line height (100px), and the difference is the glyph character height, which is slightly smaller than the font sizes.

Note that if you set the vertical alignment value to top

(or bottom

) to:

<span class="top">baseline span Text</span>

      

then the calculated height is 100px, the specified line height.



Information on why it works the way it is done is in the CCS2 specification:

http://www.w3.org/TR/CSS21/visudet.html#line-height

in particular, the part about leading and half leading.

$(document).ready(function() {
  var $container = $('.container');
  var divHeight = $container.height();
  $('.info').html('container is ' + divHeight + 'px');
})
      

div {
  font-size: 20px;
  line-height: 100px;
  outline: 1px solid red;
  position: relative; /* for demo only */
}
span {
  font-size: 40px;
  line-height: 100px; /* this value is inherited, I show it explicitly */
  display: inline-block;
  background: wheat;
}

/* the following for demo purposes... */
.info {
  font-size: 20px;
  line-height: 1;
  background-color: yellow;
}
.top {
  vertical-align: top;
}
.base {
  vertical-align: baseline;
}
.line-50 {
  position: absolute;
  border-top: 1px dashed blue;
  outline: none;
  top: 50%;
  left: 0;
  width: 100%;
}
.box-50 {
  position: absolute;
  outline: none;
  bottom: 50%;
  right: 0;
  width: 100px;
  background-color: yellow;
  font-size: 50px;
  line-height: 36px;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="info">x</span>
<br>
<br>
<div class="container">
  test text
  <span class="base">baseline span Text</span>
  <div class="line-50"></div>
  <div class="box-50">Xey</div>
</div>
      

Run codeHide result


0


source







All Articles