【问题标题】:Text line-height won't work with inline-block div container文本行高不适用于 inline-block div 容器
【发布时间】:2014-12-01 08:22:24
【问题描述】:

这里是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 和文本居中。但是为什么行高不起作用。文本未垂直居中。我认为原因可能是 line-height 在线性布局中不起作用,但父 div 是块布局。如何垂直和水平居中红色 div 和文本。文本可能会更改,所以我不想将它们设置为绝对位置并使用如下代码:

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

感谢您的帮助!

【问题讨论】:

    标签: css


    【解决方案1】:

    您可以简单地将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 评论后编辑。

    【讨论】:

    • 是的,文本居中。但是红色的div怎么了?为什么行高不起作用?
    • 感谢@chead23 的反馈。
    • 是的,vertical-align: top 完美地完成了这件事。你能告诉我为什么吗?我想知道原因。
    • @nich - 因为vertical-align:top 打破了 div 和文本必须位于同一基线上的对齐约束。
    • 没有。您的div 目前为空。把一些文字放进去,然后看看。如果内部 div 中有文本,则不需要 vertical-align
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2023-03-28
    • 2020-02-14
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    相关资源
    最近更新 更多