2015-05-04 61 views
3

这里是下面的html代码:垂直对齐:基线外元素怪高度

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

CSS代码:

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

我的问题是,为什么容器元素的高度为107px,不110px。

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

回答

0

考虑您的代码段,转载如下,并期待在黄色,右手元件的具有font-size: 50pxline-height: 36px。请注意,即使字体大小为50像素,字符(字形)所占的垂直空间也小于50像素,更像36像素。字体的设计使得有一个盒子可以容纳字符,而字形/字符则位于该盒子内。

计算出的整体框高度实际上是行高(100px)加上不同的是字形框的高度,它比字体大小的尺寸略小。

注意,如果上设置的垂直对齐值top(或bottom):

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

则计算高度为100像素,在指定行的高度。

,为什么这工作方式是这样的细节在CCS2说明书发现:

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

具体而言,大约领先半领先的一部分。

$(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>

+0

谢谢您的帮助,我改变字体家族和容器的高度为106〜108px,该textBottom - textTop = fontSize的,不是基准线 –