1

I'm currently changing a PSD design to a HTML site. I've come into an issue however. I am unable to center a certain element. I've tried all the usual tricks.

http://lowhop.net/

See here the main blue header is out of line (not centered). I tried

#slider{ position:absolute; left:0; right:0; margin-left:auto; margin-right:auto;

Before, however it didn't work reliably. (Appeared only to work on my screen resolution/browser).

Thanks

rich1334
  • 39
  • 3
  • 1
    Does it need to be positioned absolutely? Does it even need to be centered? It looks like you've positioned `div#navBar` simply by adding `margin-left: 85px`. It seems that you could use that same method for `div#slider`. – showdev Mar 01 '13 at 18:15

4 Answers4

3

You need to explicitly define a width on the element when using margin: 0 auto to center.

Block elements take up the full available viewport width unless you explicitly give them a width.

Adrift
  • 58,167
  • 12
  • 92
  • 90
  • `#slider { margin: 0 auto; z-index: 2; background-image: url(../img/sliderbg_09_09.png); width: 982px; height: 251px; }` Causes the effect below – rich1334 Mar 01 '13 at 18:14
  • Position absolute was removed. Now this has occured http://pasteboard.co/C3Fl2K1.png – rich1334 Mar 01 '13 at 18:16
2

Since you explicitly set the width of the slider DIV, you can use another trick to center it:

#slider 
{
  z-index: 2;
  background-image: url(../img/sliderbg_09_09.png);
  position: absolute;
  display: block;
  width: 982px;
  height: 251px;
  left: 50%;
  margin-left: -491px; /** half DIV width */
}

I'd probably steer away from having this as a position absolute DIV, doesn't look like it needs it but that's a quick and dirty centering :)

Hope that helps

ottis
  • 216
  • 1
  • 3
0

If you must use absolute positioning, you can use something like my answer here.

Basically, you declare an explicit width for your element, then give it

left: 50%;
margin-left: -[your width/2];
Community
  • 1
  • 1
chipcullen
  • 6,840
  • 1
  • 21
  • 17
0

like user showdev mentioned :

Does it need to be positioned absolutely? Does it even need to be centered? It looks like you've positioned div#navBar simply by adding margin-left: 85px. It seems that you could use that same method for div#slider.

you have

#navBar {
  background-image: url("../img/navbg_07.png");
  display: block;
  height: 38px;
  margin-left: 85px; /* attention on this */
  margin-top: 31px;
  position: relative;
  width: 879px;
  z-index: 1;
}

and this

#slider {
  background-image: url("../img/sliderbg_09_09.png");
  display: block;
  height: 251px;
  position: absolute;
  width: 982px;
  z-index: 2;
}

so, try 'margin-left: 85px;' your #slider.

Milche Patern
  • 19,632
  • 6
  • 35
  • 52