V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
manyfreebug
V2EX  ›  CSS

给 span 和 div 设置 line-height 时,为什么会出现这种差异?(如图) 。我以为它们会呈现一样的效果

  •  
  •   manyfreebug · 2020-03-31 21:07:37 +08:00 · 2134 次点击
    这是一个创建于 1457 天前的主题,其中的信息可能已经有所发展或是发生改变。
    可以在这里查看两者的运行效果,两者代码基本是一样的,但其中一个标签是 div,另一个是 span
       div:  https://jsbin.com/cinesiwuyi/edit?html,css,output 
       span: https://jsbin.com/xikeluzode/edit?html,css,output
    

    第 1 条附言  ·  2020-03-31 23:33:49 +08:00
    更新下链接:
       div:  https://jsbin.com/wabamufabi/edit?html,css,output
       span: https://jsbin.com/xikeluzode/edit?html,css,output
    
    3 条回复    2020-03-31 23:09:54 +08:00
    P233
        1
    P233  
       2020-03-31 21:40:57 +08:00   ❤️ 1
    div 默认 "display: block"
    span 默认"display: inline"

    给 span 加一个 "display: block" 两者的表现就一样了

    它俩的区别在于 block 与 inline 元素在处理 line-height 小于 font-size 时的方式不同。
    loading
        2
    loading  
       2020-03-31 21:41:15 +08:00 via Android
    审查元素,听说过吗?
    old9
        3
    old9  
       2020-03-31 23:09:54 +08:00   ❤️ 2
    夹在两个 div 之间的 span 会产生一个 anonymous block box 。虽然 span 设置了 line-height:0,但是其所在的这个 anonymous block box 还占据着空间。
    这个 box 的属性会继承包裹它的非匿名 box,在你的例子中是 body 。你可以给 body 一个 line-height:0,同时给 .content 一个 vertical-align:top/bottom 来消除这个间隔。

    具体原理其实挺复杂,要了解这个间距怎么来的,需要知道 line box,inline box,vertical-align, line-height 等一大堆逻辑,需要去仔细啃啃 spec
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4165 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:15 · PVG 18:15 · LAX 03:15 · JFK 06:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.