文本行高不适用于内联块div容器 [英] Text line-height won't work with inline-block div container

查看:46
本文介绍了文本行高不适用于内联块div容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 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和文本在垂直和水平方向上居中.文本可能会更改,所以我不想设置它们的绝对位置并使用如下代码:

The red div and text are centered. But why line-height does not work. The text is not centered vertically. I think the reason might be the line-height not work in linear layout, but the parent div is block layout. How to center the red div and text both vertically and horizontally. The Text might be changed, so I do not want set them absolute position and use code like:

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

感谢您的帮助!

推荐答案

您可以将 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评论后编辑.

Edit after @chead24 comment.

这篇关于文本行高不适用于内联块div容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆