Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

absolute vertical centering elements

I've tried a lot of methods to center the children elements absolute vertical center but couldn't be success with any techniques.

Here's one example 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.e I cannot wrap .foo with parent div and even cannot wrap all childrens within .foo with a div.

So, how can I vertically center them over the full window ?

like image 770
Bhojendra Rauniyar Avatar asked Aug 11 '26 13:08

Bhojendra Rauniyar


2 Answers

You could achieve this by using the css flexbox layout 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>
like image 143
Anonymous Avatar answered Aug 14 '26 12:08

Anonymous


Here's a possible solution:

Make the .foo element a table, and every child a table-row.

Then add an after and before pseudo elements, also as rows, forcing them to expand with min-height: 100%;.

The inner elements will then squeeze in the middle:

Updated Fiddle

.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>
like image 42
LcSalazar Avatar answered Aug 14 '26 10:08

LcSalazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!