Day: March 25, 2010

  • No way to control inline elements’ height

    今天在 css 里遇上一个以前不曾注意的细节:
    假设<a>和<img>的 border, margin 和 padding均为0,一个被<a> wrapped 的 <img> (<a><img/></a>) 比单独一个 <img/> 在 Firefox 中 render 要高 3px,在 chrome 和 ie 下也会高一些(但我未测量数值)。

    实例代码

    
    <style type="text/css">
    a { text-decoration:none; }
    a, img { border:0; padding:0; margin:0; }
    .col-1 { float:left; text-align:right; width:49%; }
    .col-2 { float:right; text-align:left; width:49%; }
    .line { height:1px; border-top:1px solid orange; }
    </style>
    
    <div class='col-set'>
    <div class='col-1'>
    <a href="#">
    <img src="not-lineup.jpg"/>
    </a>
    <div class='line'>&nbsp;</div>
    </div>
    <div class='col-2'>
    <img src="not-lineup.jpg"/>
    <div class='line'>&nbsp;</div>
    </div>
    </div>
    
    
    Inline elements 不等高实例截图
    Inline elements 不等高实例截图

    我想了很久才知道这都是因为<a>和<img>是inline elements。Inline elements 有一些特性

    • they flow with text.
    • they have line-height.
    • the element height and width is dependent on the content and will not collapse to the borders of the parent element.

    Inline elements 没有 height,在上例中也无法用 line-height 去控制高度:<a>的底部与<img>的底部有 3px 间距,我试遍我能想到的所有 css 属性都无法消除这个间距,除非——

    将<a>设为display:block!Block elements 的 border, margin 和 padding 都是有效的,控制高度就不是问题了。