vertical-align之不深入理解

2017-07-18  本文已影响0人  喂虾米的鱼

1. 属性定义

先来看下官方定义:

This property affects the vertical positioning inside a line box of the boxes generated by an inline-level element.

重点:
图1
理解:

如图所示

关于 line box 盒子更详细的可以看看这篇CSS float浮动的深入研究、详解及拓展(一)

2. 取值

取值很多:

baseline | sub | super | top | text-top | middle | bottom | text-bottom | <percentage> | <length> | inherit

本文重点关注baseline 和 middle;

1. 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.

重点:
理解:

定义里提到如果盒子没有baseline,则将盒子的margin底部和linebox的baseline对齐。可以在这将没有baseline 的盒子的margin底部所在线理解为它的baseline方便后续理解。我们来看个例子。

<p class='p1'>
    <span>xixi</span>haha
</p>
<p class='p2'>
    <span></span>haha
</p>
<p class='p3'>
    <span>xixi</span>haha
</p>
span{
        display: inline-block;
        background: #eee;
        height:50px;
        width:40px;}
.p3 span{
       overflow: hidden;}

如图所示 中图和右图的基线位置一致。这里提下overflow的value为visible之外的值的情况下inline-block表现的和里面是空的情况一样,baseline是它的margin底部。
另外我试了下几个常见的元素,图片元素 textarea的margin底部就是它的基线。 input[type=text]的基线是其内部文字的基线,不管有没有输入文字。

2. middle

Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

重点:
理解:
           .s1{
                height: 50px;
            }
            .s2{
                height: 60px;
            }
            .s3{
                height: 59px;
            }
    <p class='p1'><span class="s1"></span><span class="s2"></span>xi</p>
    <p class='p2'><span class="s1"></span><span class='s2'></span>xi</p>
    .s1{
        height: 30px;
    }
    .s2{
        height: 60px;
    }
    p{
        float: left;
        margin-left: 10px;
    }
    .p1 .s1{
        vertical-align: middle;
    }
    .p2 .s2{
        vertical-align: middle;
    }

3. 常见的间隙

   <div><span></span></div>
   <div><span></span><i>xixi</i></div>
       div{
           background: #eee;
           width: 60px;
           float: left;
           margin-left: 10px;
       }
       span,i{
           display: inline-block;
       }
       span{
           width: 20px;
           height: 60px;
           background: #ddd;
       }
       i{
           background: #ccc;
       }

完结撒花嘻嘻(●'◡'●)。

参考资料

深入理解 CSS:字体度量、line-height 和 vertical-align
我对CSS vertical-align的一些理解与认识(一)
Vertical-Align: All You Need To Know

上一篇 下一篇

猜你喜欢

热点阅读