inline-block元素设置overflow:hidden属性导致相邻行内元素向下偏移

85 篇文章 1 订阅

在表单修改界面中常会使用一个标签、一个内容加一个修改按钮来组成单行界面,如下所示:


那么在表单总长度受限的情况下,当中间的邮箱名称过长时,会遮盖到旁边的按钮。

我们可以把中间邮箱设定最大宽度,然后对于长度超出部分设置overflow: hidden来解决这个问题。

但是这可能会引发另一个经典的 baseline 对齐问题,也就是本文要讨论的主要问题。

1. 问题现象

我们先给出一个在线实例:

http://wow.techbrood.com/fiddle/15438

我们可以看到当给中间的 inline-block 元素p添加overflow: hidden属性后,其左右相邻元素被奇怪的向下拉动了一定的距离。


2. 解决方法

常用的解决方法是为上述inline-block元素添加vertical-align: bottom。你可以在上面的例子中在线测试下。

3. 问题原因

W3的规范对此行为有明确规定:

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

我们从规范中可以知道当一个inline-block元素被设置overflow非visible属性值后,其baseline将被强制修改为元素下外边沿。

我们知道默认情况下,baseline为字符x的底线位置且vertical-align属性值为baseline。

此外由于div包含块中只有行内级别的元素,所以将生成一个IFC(行内格式化上下文)来规定其中元素的渲染规则。

按照IFC布局规则,垂直方向上对齐遵照vertical-align属性(请参考阅读:http://techbrood.com/Guide/h5b2a?p=css-ifc),

那么p元素两边的2个匿名line box将被迫向下移动一个偏移值来和p元素对齐。


那么可能有人要进一步追问了,为什么W3要做如此奇怪的规定呢?

这是因为overflow被设置为非visible值,将使得该inline-block元素中的last line box的渲染处于不确定状态(浏览器可能渲染也可能不渲染),

这让保持默认规则的baseline也处于不确定状态,那么索性就规定以确定的下外边沿来作为baseline。

"baseline" - 
Align the baseline of the box with the baseline of the parent box. If the box does not have a baseline, align the bottom margin edge with the parent's baseline.


4. 偏移的计算

上述的向下偏移量,实际上就是inline-block元素的默认baseline和其下外边沿的距离。

shift = D(descent) part of Glyph(字母下降部分)+ bottom half-leading


5. 参考链接:

1. http://techbrood.com/Guide/h5b2a?p=css-line-height

2. http://www.w3.org/TR/CSS2/visudet.html#propdef-line-height

3. http://www.w3.org/TR/CSS2/visudet.html#leading


by iefreer

  • 19
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值