行高不垂直居中内联块

  • 本文关键字:垂直居中 高不 html css
  • 更新时间 :
  • 英文 :


我试着像这样垂直居中一个内联块:

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

但是span不是垂直居中的。为什么?

因为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>

最新更新