Text string-height will not work with div container
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 the text are centered. But why the line-height does not work. The text is not centered vertically. I think the reason may be the line-height not working in the linear layout, but the parent div is the block layout. How to center a red div and text both vertically and horizontally. The text can be changed, so I do not want to set their absolute position and use the code:
margin-left: -25px;
margin-top: -25px;
left: 50%;
top: 50%;
Thanks for the help!
+4
1 answer
You can simply add vertical-align: topto .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 comment @ chead24.
+5