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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With