Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text line-height won't work with inline-block div container

Tags:

css

Here is the 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;
}

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%; 

Thanks for the help!

like image 495
SPG Avatar asked Dec 01 '14 08:12

SPG


1 Answers

You can simple add vertical-align: top to .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>

Edit after @chead24 comment.

like image 110
Alex Char Avatar answered Sep 28 '22 14:09

Alex Char