I need to center text vertically and horizontally. Is there a simple way to do this for the following code?
<div style="display: block; height: 25px;">
<span id="ctl_txt" style="background-color: rgb(255, 0, 0);">
Basic
</span>
</div>
For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.
Answer: Use the CSS line-height property Suppose you have a div element with the height of 50px and you have placed some link inside the div that you want to align vertically center. The simplest way to do it is — just apply the line-height property with value equal to the height of div which is 50px .
To center text in CSS, use the text-align property and define it with the value 'center.
Another way to do this, different from @Jose, is to use
display:table;
and display:table-cell
like this
div{
display:table;
height:125px; //JUST FOR SHOW
width:125px; //JUST FOR SHOW
}
span{
background-color: rgb(255, 0, 0);
display:table-cell;
vertical-align:middle;
text-align:center;
}
Then vertical-align:middle;
and text-align:center;
do the work.
Example: http://jsfiddle.net/jasongennaro/unfwL/1/
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