Joey
Joey

Reputation: 2792

Vertically center elements in IE9 using CSS

I was trying to use the following code to center a <div> inside another <div> by using CSS, but it only works in Chrome, not IE9 and Firefox 13.0.1. The following is my HTML file:

<!DOCTYPE HTML>
<html>
<head>
    <link type="text/css" rel="stylesheet" href="test.css">
    <title>test</title>
</head>
<body>
    <div class="container">
        <div class="center">abc</div>
    </div>
</body>
</html>

The following is my CSS file:

.container{
    position: relative;
    border: 1px solid black;
    width: 600px;
    height: 400px;
    position: relative;
}

.center {
    border: 1px solid blue;
    width: 300px;
    height: 200px;
    position: absolute;
    margin-left: 50%;
    margin-top: 50%;
    top: -100px;
    left: -150px;
}

I found another easier problem. If I remove the code top: -100px in the above CSS file, the bottom border of inner div is supposed to exactly cover the outer div bottom border, because the inner div's height is 200px and the outer div's height is 400px, and then set the inner div to margin-top: 50%. Both divs' bottom borders should be together, but they are not.

I also found out that margin-top:50% depends on outer div's width. If the width is longer, then margin-top: 50% will make inner div go down further. It is so weird. Does anyone knows the reasons?

Upvotes: 3

Views: 6255

Answers (1)

Jonathan S.
Jonathan S.

Reputation: 2228

When using percentages for margins, the percentages are always relative to the width of the containing element (source).

Swap your margin-top for top and margin-left for left, and it should work fine:

.container{
    position: relative;
    border: 1px solid black;
    width: 600px;
    height: 400px;
}

.center {
    border: 1px solid blue;
    width: 300px;
    height: 200px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -100px;
    margin-left: -150px;
}

http://jsfiddle.net/rcnWy/1/

Upvotes: 2

Related Questions