3

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?

0

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

3 Comments

You can also shorten the declaration by eliminating everything below position: absolute; and adding margin: 100px 150px;.
That's a good point. I assumed this was a contrived example and the real version would be using a container with non-fixed dimensions. If the container has fixed dimensions, though, you can definitely simplify.
Your method is good. My container is actually not fixed size. I think I was just blind because my mistake is kinda foolish. I put these in the wrong places. Thanks for helping.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.