I have a centered layout using margin:0 auto;, but one of my child divs isn't positioning itself absolutely (relative to its parent). The page looks fine until the window is resized. Then the child div gets pushed to the very right, and the top image (in another div) gets clipped.

What code changes do I need to make?

Here's the CSS:

body {
 padding: 0;
 margin: 0;
 display: table;
 text-align: center;
 background: #FFF url("/images/businessmanbg.jpg") no-repeat center top;
 width: 100%;
#wrapper {
 margin: 0 auto;
 position: relative;
#container {
 margin: 0 auto;
 text-align: left;
 position: relative;
#topbar {
 background: #036 url("/images/topbar.jpg") no-repeat center top;
 position: relative;
 margin-top: -22px;
 display: block;
 height: 111px;
 width: 100%;
#content {
 background: url("/images/copy-bg.png");
 padding: 10px;
 position: absolute;
 margin-left: 900px;
 margin-top: 50px;
 text-align: left;
 width: 450px;

2 answers

This was chosen as the best answer

Leslie -

The background isn't showing up because both inside DIVs are position absolute which removes them from the document flow - so that one container sees that effectively, nothing is in it.

Here's what I did to make it look right in Firefox - I haven't tested in any other browsers, but it's a start:

#topbar - remove position absolute, and left and top values

#topbar h1 - add margin:0;

#content - remove position absolute and left and top values. add position:relative; left:660px; or a value around there to get it just where you want it.

Does that work?

Answered over 8 years ago by webcodeslinger
  • That works wonderfully! I was told another solution was to remove the absolute positioning from #topbar and #content, and add a margin-left to #content. Thanks so much! Leslie N over 8 years ago

Hi Leslie,

I believe that the problem is that your relatively positioned container is 100% width - your inner item will always move around because that width is always changing.

Try putting the businessman graphic as background on an inner DIV, give that DIV position:relative; and a width, and then put #content inside that, with absolute positioning.

In addition, using absolute positioning really requires use of two of the following values: left, top, right, bottom. If you don't use those, all bets are off as far as positioning goes.

I would remove your left and top margin on #content, and instead use top:120px; and right:445px; That seems to put that DIV where you want it.

Answered over 8 years ago by webcodeslinger
  • Thanks so much, Jennifer! That's really helpful. I think I'm getting closer to what I want, but I can't tell because moving the background to the #container DIV made the image disappear, so I can't tell if the #content div is in the right place all the time. It looks like it's not moving, though, so I'm almost there. Could you take a look at the test page again to help me see where the background went? Leslie N over 8 years ago