http://jsfiddle.net/fQv97/
HTML
<div class="table-cell"> My text, should be align middle </div>
CSS
.table-cell { height: 200px; width: 200px; vertical-align: middle; background: #eee; display: table-cell; position: absolute; }
Problem
The text should be placed in the middle of my "table cell". Everything works as expected until I add "position: absolute". Now it can't place my content in the middle any more? Why not? It still knows my height and width because I set it in my CSS.
Any clever workaround for this?
To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
To place an item at the top or bottom of its cell, insert the "VALIGN=" attribute within the code for that cell. To vertically align an entire row (e.g., placing all data in that row at the tops of the cells), insert the "VALIGN=" attribute within the code for that row.
Answer: Use the CSS vertical-align Property You can align an image vertically center inside a <div> by using the CSS vertical-align property in combination with the display: table-cell; on the containing div element.
The vertical-align property sets the vertical alignment (like top, bottom, or middle) of the content in <th> or <td>. By default, the vertical alignment of the content in a table is middle (for both <th> and <td> elements).
Everything works as expected until I add "position: absolute". Now it can't place my content in the middle any more? Why not?
position: absolute
forces display: block
, read number two here.
As for a workaround, I think you'll have to wrap it in another element:
<div class="table-cell-wrapper"> <div class="table-cell"> My text, should be align middle </div> </div> .table-cell-wrapper { position: absolute; } .table-cell { height: 200px; width: 200px; vertical-align: middle; background: #eee; display: table-cell; }
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