2

I am looking to center a large div that reaches beyond the screen. This concerns having a large .container div about 1920px wide, with the actual content being centered inside .container in a div with a class of .content, about 1200px wide.

I manage to center one in the other, but centering .container when it's boundaries are off-screen is not working. It puts the left border against the left border of the browser.

[ |   [content]   | ]

Legend:
| = screen edge
[ ] = div edge

.content must always be centered within .container so that the background's position related to the foreground does not change.

<div class="container">
  <div class="content">
    <section></section>
  </div>
</div>
Cody Guldner
  • 2,888
  • 1
  • 25
  • 36
  • I mean... this seems like a terrible idea. I'd set container to 100% width and content to `margin: auto` and I know that doesn't solve your problem if container is 1920 wide, but what you want just seems like a bad idea. I can think of a possible solution with javascript but not with CSS only. – Leeish May 08 '13 at 21:21
  • There's an answer [here](http://stackoverflow.com/questions/8149747/aligning-image-to-center-inside-a-smaller-div#8150196) that might work for you. Here's a [fiddle](http://jsfiddle.net/x62nV/285/). – showdev May 08 '13 at 21:25
  • Will .container always be 1920px wide? – Turnip May 08 '13 at 21:30
  • @3rror404 yes, I have a background that is 1920px wide, and the content overlaying always needs to have a static position on top of that, even if the user is using like a 1280x1024 monitor. – Rudy van Sloten May 08 '13 at 21:35
  • @Leeish I'll take any solution really. Even JS. I thought it'd be possible with CSS. – Rudy van Sloten May 08 '13 at 21:35

1 Answers1

6

If you know the width of .container you can do this:

.container {
    position: relative;
    left: 50%;
    margin-left: -960px; /* Negative margin half of the element width */
}

Here's a (dirty) jQuery alternative if you didn't know the width of .container. Esssentially the same result, you just need to calculate the negative margin by halving the width:

CSS:

.container {
    position: relative;
    left: 50%;
}

jQuery:

var elWidth = (($('.container').width())/2)*-1;

$('.container').css('margin-left', elWidth);

DEMO

Turnip
  • 35,836
  • 15
  • 89
  • 111
  • So far, this seems to be working quite perfectly. My final code: .container { width: 1920px; height: 1080px; background-image: url(images/bg.png); position: absolute; left: 50%; margin-left: -960px; z-index: -10; } – Rudy van Sloten May 08 '13 at 21:41
  • I have the static width, but I'll definitely keep this in mind. – Rudy van Sloten May 08 '13 at 21:56