Absolute vertical centering elements
I have tried many methods to center the elements of absolute vertical center elements, but could not be successful with any methods.
Here's an example of what I've tried :
html (cannot change):
<div class="foo">
<h1>blah blah</h1>
<p>foo</p>
<p>bar</p>
</div>
CSS
.foo{
position: absolute;
top: 0;
bottom: 0;
background: yellow;
}
.foo:before{
content: "";
display: inline-block;
vertical-align: middle;
height: 100%;
}
Please note, I cannot change the markup. I can't wrap a .foo
parent div and can't even wrap all the children in .foo
a div.
So how can I vertically center them all over the window?
source to share
You can achieve this using css flexbox like this:
JSFiddle - DEMO
.foo {
position: absolute;
top: 0;
bottom: 0;
background: yellow;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
flex-wrap: wrap;
/* align-items: center; */
}
h1, p {
margin:0;
}
<div class="foo">
<h1>blah blah</h1>
<p>foo</p>
<p>bar</p>
</div>
source to share
Here's a possible solution:
Make the element a .foo
table and each child table-row
.
Then add pseudo-elements after
and before
, just like strings, forcing them to expand with min-height: 100%;
.
The inner elements are then squeezed in the middle:
.foo{
position: absolute;
top: 0;
height: 100%;
background: yellow;
display: table;
}
.foo:before, .foo:after {
content: "";
display: table-row;
min-height: 100%;
}
.foo > * {
display: table-row;
vertical-align: middle;
height: 0;
}
<div class="foo">
<h1>blah blah</h1>
<p>foo</p>
<p>bar</p>
</div>
source to share