user1452062
user1452062

Reputation: 805

Vertical align text in an absolute positioned div

I would like to center vertically the text inside my div, but vertical-align:middle not working.

This is my css:

body,html {
    height:100%;
    min-height:100%;
}
#container {
    position:relative;
    width:300px;
    height:70%;
    background:red;
}

#box {
    position:absolute;
    bottom:30px;
    background:yellow;
    height:20%;
    vertical-align:middle;
    width:100%;
    text-align:center;
}

This is my html:

<div id="container">
    <div id="box">
        <p>text</p>
    </div>
</div>

I tried with margin from top with %, but it's not the best solution. Here is my online version: http://jsfiddle.net/f2qf031h/

Upvotes: 0

Views: 776

Answers (2)

Erik Svedin
Erik Svedin

Reputation: 1286

One way of doing it is with flexbox layout.

By setting:

#box {
   ...
   display:flex;
}

#box p{
    align-self:center;
    text-align:center;
    width:100%;
}

jsfiddle: http://jsfiddle.net/f2qf031h/2/

Upvotes: 2

Romo Daneghyan
Romo Daneghyan

Reputation: 2189

Try this code

#box {
    position: relative;
    top:50%;
    transform: translateY(-50%);
    background:yellow;
    height:20%;
    width:100%;
    display: table; 
    overflow: hidden;
    text-align:center;
}

Upvotes: 0

Related Questions