In the quest to center text of unknown length within a div, challenges arise. Constraints limit its size to a certain extent, making it unclear whether one or two lines will be needed. As such, traditional methods like line-height
are not viable options. Attempts with display: table-cell
prove futile as they disrupt the layout. Certain positioning tricks using top
cannot be employed due to other positional requirements.
To better understand this dilemma, refer to the following example.
Visual Representation:
The Original Code:
HTML:
<div class="background"> </div>
<div class="TileText">MyText - Another long, long, long text</div>
CSS:
.background{
background-color:#000;
height: 400px;
width: 100%;
}
.TileText{
position: relative;
top: -135px;
max-width: 200px;
height: 80px;
background-color: #FFF;
color: #black;
clear: both;
padding-left: 10px;
}
The Current State:
HTML:
<img src="images/castle.png" width="300" height="333" title="Castle" alt="Castle" />
<div class="TileTextWrapper">
<div class="TileText">Text</div>
</div>
CSS:
.TileTextWrapper{
position: relative;
top: -135px;
max-width: 200px;
height: 80px;
background-color: #FFF;
color: #57abe9;
clear: both;
padding-left: 10px;
display: table;
}
.TileText{
display: table-cell;
vertical-align: middle;
}
An Update:
The text is now vertically aligned properly. However, concerns persist regarding browser compatibility when using display: table
.