I have a scenario like this where I would like to have an image with width 100% as background. Next i want to align a two column layout text on the middle of image. I use display table cell and vertical align: middle and it is not working as expected.
Expected outcome is the two column layout is in the middle. Note: The image must serve as background with width 100% and height scale according to browser width.
* {
margin: 0;
padding: 0;
}
<div style="position: relative;">
<img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;">
<div style="display: table; vertical-align: middle; padding-top: 100px;">
<div style="display: table-cell; width: 120px;">
Left Column
</div>
<div style="display: table-cell;">
<p>
Right Column Top
</p>
<p>
Right Column Bottom
</p>
</div>
</div>
</div>
</div>
If flexbox
is an option it can be easily done removing the table and using this:
display: flex;
justify-content: center;
align-items: center;
height: 100%;
Note that I have removed the inline style and added in classes for illustration:
* {
margin: 0;
padding: 0;
}
.container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
<div style="position: relative;">
<img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
<div class="container">
<div class="wrapper">
<div style="width: 120px;">
Left Column
</div>
<div>
<p>
Right Column Top
</p>
<p>
Right Column Bottom
</p>
</div>
</div>
</div>
</div>
If you want to stick with tables, here is the solution:
Add height: 100%
to table
and vertical-align: middle
to the table-cell
s too for vertical alignment.
Add margin: 0 auto
for horizontal alignment.
Demo below:
* {
margin: 0;
padding: 0;
}
.container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.wrapper {
display: table;
vertical-align: middle;
height: 100%;
margin: 0 auto;
}
.wrapper > div {
display: table-cell;
vertical-align: middle;
}
.wrapper > div:first-child {
width: 120px;
}
<div style="position: relative;">
<img src="https://www.math.nmsu.edu/~pmorandi/math112f00/graphics/rectangle.gif" style="width: 100%; line-height: 0;" />
<div class="container">
<div class="wrapper">
<div>
Left Column
</div>
<div>
<p>
Right Column Top
</p>
<p>
Right Column Bottom
</p>
</div>
</div>
</div>
</div>