1

I'm trying to display a block in the center of the window using margin auto.

My code is

<div class="centre-element"> This box is coming at the center of the window. </div>

CSS

.centre-element{
    width: 200px;
    height: 100px;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
}

This works in all the browsers I tested except in IE7. Is there any help for this?

Appreciate any help.

Rupam Datta
  • 1,849
  • 1
  • 21
  • 36
  • possible duplicate of [CSS: Vertically align div when no fixed size of the div is known](http://stackoverflow.com/questions/7206640/css-vertically-align-div-when-no-fixed-size-of-the-div-is-known) – NGLN Feb 08 '13 at 10:11

2 Answers2

2

you can't center a div vertically using margin: auto, but you could try this:

.centre-element {
  top: 50%;
  margin-top: -50px; /* height/2 */
}

Edit:

Here is an example: http://jsfiddle.net/ZD432/

Barnee
  • 3,212
  • 8
  • 41
  • 53
  • You are almost there. Do same thing with left: `left: 50%; margin-left: -100px`. +1 anyway :) – Morpheus Feb 08 '13 at 10:18
  • @Morpheus - No need to do the same thing with "left" as "margin:0 auto;" will do the trick. – Billy Moat Feb 08 '13 at 10:19
  • @Billy Moat if `margin:0 auto;` will be added **before** `margin-top: -50px` – Morpheus Feb 08 '13 at 10:21
  • @Morpheus Billy Moat's right. And you could use: `margin: -50px auto 0;` – Barnee Feb 08 '13 at 10:24
  • 1
    [This is proof that you both are not right](http://jsfiddle.net/8uZCD/). [And this is how it should be](http://jsfiddle.net/8uZCD/1/) – Morpheus Feb 08 '13 at 10:32
  • @Morpheus you're right in one way... But Rupam Datta used `position:absolute; left:0; right:0;` so in this case you can use `margin: -50px auto 0;` (and in this way you'll have a dynamic width to) – Barnee Feb 08 '13 at 10:44
  • @Barnee please post the complete answer with [jsfiddle](http://www.jsfiddle.net) example – Morpheus Feb 08 '13 at 10:53
  • @Barnee Thanks for your solution. But as Morpheus said, I have to use left: 50% and margin-left: -100px to get it worked completely. – Rupam Datta Feb 19 '13 at 06:45
0
.centre-element{
   width: 200px;
   height: 100px;
   margin: auto;
   padding: auto;    
}
aishazafar
  • 1,024
  • 3
  • 15
  • 35
  • Thanks Morpheus. I usually use above code to bring a div in center of the window(horizontally). But your comment made my concept more clear about margin and padding. – aishazafar Feb 08 '13 at 12:17