Marko Kevac
Marko Kevac

Reputation: 2982

How do I make contents in the middle box centered vertically?

How do I make contents in the middle box centered vertically?

http://jsfiddle.net/9pYSU/:

HTML:

<body>
    <div id="header">Header content</div>
    <div id="bodyBox">Body content</div>
    <div id="footer">Footer content</div>
</body>

CSS:

body {
}
body > div {
    border-radius:10px;
    border:2px solid #AAA;
    padding:10px;
    text-align:center;
}
#header {
    position:absolute;
    height:50px;
    top:10px;
    right:10px;
    left:10px;
}
#bodyBox {
    position:absolute;
    right:10px;
    top:94px;
    bottom:94px;
    left:10px;
    border-color:#35C12E;
    background-color:#f0f4f0;
}
#footer {
    position:absolute;
    height:50px;
    bottom:10px;
    right:10px;
    left:10px;
    border-color:#B24842;
}

Upvotes: 0

Views: 62

Answers (2)

Terry
Terry

Reputation: 66173

I do not typically advocate forcing table displays, but it is convenient when working with older browsers. There are two other alternatives: using CSS transforms or Flexbox (the latter of which is more recent and not as widely supported as the former).

Both methods require wrapping your body content in an additional element, say, <div>:

<div id="bodyBox">
    <div>
        Body content
    </div>
</div>

Solution 1: CSS Flexbox

The other way is to use CSS flexbox model (see demo) to achieve the same effect. You will have to add the following styles to #bodyBox:

#bodyBox {
    display: flex;
    align-items: center;
    justify-content: center;
}

Solution 2: CSS Transforms

The trick here is to position the inner <div> absolutely at 50% from the top and left of its containing parent. However, in order to offset the positioning due to the <div>'s computed dimensions, we will use CSS transforms to do so. You might have to use vendor prefixes for transform to work. **However, a major caveat is that the dimensions of the containing parent, #bodyBox has to be explicitly predefined, as absolutely positioning its children takes them out of the document flow, causing the parent element's height to collapse.

#bodyBox > div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

Upvotes: 1

Kevin Lynch
Kevin Lynch

Reputation: 24723

You need to add vertical-align. Add a div wrapper and give it a display value of table within your current div. Then put another div within that and give it a display value of table-cell.

DEMO http://jsfiddle.net/9pYSU/2/

#bodyBox div {
    display: table;
    vertical-align: middle;
    height: 100%;
    width: 100%;
}
#bodyBox div div {
    display: table-cell;
    vertical-align: middle;
    height: 100%;
}

Upvotes: 0

Related Questions