文本行高不会与内联块div容器一起使用

时间:2014-12-01 08:22:25

标签: css

这是jsfiddle。 HTML:

<div class="main">
    <div class="div1"></div>
    Center with Red!
</div>

CSS:

.main{
    height: 50px;
    width: 100%;
    background-color: #000000;
    text-align: center;
    color: #ffffff;
    line-height: 50px;
    font-size: 24px;
}

.div1{
    display: inline-block;
    width: 50px;
    height: 50px;
    background-color: #ff0000;
}

红色div和文本居中。但为什么行高不起作用。文本不是垂直居中的。我认为原因可能是线条高度在线性布局中不起作用,但父div是块布局。如何垂直和水平居中红色div和文本。文本可能会被更改,所以我不想设置它们的绝对位置并使用如下代码:

margin-left: -25px;
margin-top: -25px;
left: 50%;
top: 50%; 

感谢您的帮助!

1 个答案:

答案 0 :(得分:6)

您可以简单地将vertical-align: top添加到.div1

.main {
  height: 50px;
  width: 100%;
  background-color: #000000;
  text-align: center;
  color: #ffffff;
  line-height: 50px;
  font-size: 24px;
}
.div1 {
  display: inline-block;
  width: 50px;
  height: 50px;
  background-color: #ff0000;
  vertical-align: top;
}
<div class="main">
  <div class="div1"></div>
  Center with Red!
</div>

@ chead24评论后编辑。

相关问题