Lars Mandsert
Lars Mandsert

Reputation: 15

How to use vertical-align: middle

live: http://jsfiddle.net/8hAv3/

#main {
    width: 100px;
    height: 100px;
    background-color: red;
}
#sub {
    width: 100%;
    height: 100%;
    background-color: blue;
    vertical-align: middle;
}

<div id="main">
    <div id="sub">TEXT</div>
</div>

Why in this example vertical-align not working? How can i make it? I dont want use margin, padding and set height in px. Is this possible?

Upvotes: 0

Views: 165

Answers (6)

Khanh TO
Khanh TO

Reputation: 48982

Just give the div a line-height.

 #main {
    width: 100px;
    height: 100px;
    background-color: red;
}
#sub {
    width: 100%;
    height: 100%;
    background-color: blue;
    line-height:100px;
}

Fiddle

This solution does not use display:table and display:table-cell as display:table and display:table-cell are not browsers friendly, some older browsers do not support

Upvotes: 0

Daniel
Daniel

Reputation: 4173

This should work:

#main {
    width: 100px;
    height: 100px;
    background-color: red;
    display: table;
}
#sub {
    display: table-cell;
    height: 100%;
    width: 100%;
    background-color: blue;
    vertical-align: middle;
}

http://jsfiddle.net/8hAv3/2/

Upvotes: 1

Richard Young
Richard Young

Reputation: 462

You have to give the element #sub a line height, otherwise the browser doesn't know how high it is to vertically align it.

Upvotes: 0

Tim Wasson
Tim Wasson

Reputation: 3656

You need to use display:table on the main container and display:table-cell on the child. Illustrated here: http://jsfiddle.net/8hAv3/1/

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

you have to use a

display:table-row; 
display:table-cell; or 
display:table;

along with the vertical-align style, not sure which exact display value it has to be but it needs to be one of the table ones.

Upvotes: 0

Matt Berkowitz
Matt Berkowitz

Reputation: 975

if you just want to vertically center text in a fixed height box I would use line-height:100px to do it

Upvotes: 0

Related Questions