2016-09-22 100 views
1

我试图垂直居中直列块这样的:行高不垂直中心内联块

div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: red; 
 
    line-height: 50px; 
 
} 
 
span { 
 
    display: inline-block; 
 
    width: 20px; 
 
    height: 20px; 
 
    background: white; 
 
}
<div> 
 
    <span></span> 
 
</div>

但跨度不垂直居中。为什么?

回答

2

因为line-height设置了文字的基线位置(span的底部)。由于您的跨度是20px很高,你必须添加的一半,为line-height

div { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: red; 
 
    line-height: 60px; 
 
} 
 
span { 
 
    display: inline-block; 
 
    width: 20px; 
 
    height: 20px; 
 
    background: white; 
 
}
<div> 
 
    <span></span> 
 
</div>

+0

它仍然不居中。跨度为16px,下方为14px。 – Gropai