css 100% width div not taking up full width of parent

panzhuli picture panzhuli · Aug 24, 2011 · Viewed 119.3k times · Source

I have two divs on a page. a grid-container that takes a background and an internal grid that needs to be positioned in the center of the other grid. My css:

html, body{ 
  margin:0;
  padding:0;
  width:100%;
}
#grid-container{
  background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
  width:100%;
}
#grid{
  width:1140px;
  margin:0px auto;
}

At this point, the bg image of the #grid-container only fills the window, not the full width of the html. The symptom of this is that if you narrow the browser window so that a horizontal scrollbar is required and refresh the page, the bg image ends where the browser window ends. When I scroll to the right, the bg image is not there. Ideas?

EDIT: ok, per requests, I've edited my css/html. When I remove the width designation in the #grid-container, it shrinks to the width of the container within, which is even worse. Here's what I have now:

html, body{ 
  margin:0;
  padding:0;
  min-width:1140px;
}
body{
    background:url(../images/page-background.jpg) repeat-x top left !important; 
    height:100%;
}
#grid-container{
  background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
  padding-top:1px;
}
#grid-container2{
  width:1140px;
  margin:0px auto;
}
.clearfix:after {
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}

and the html:

<!DOCTYPE HTML>
<html>
<head>
---
</head>

<body>
...
<div id="grid-container" class="clearfix">
<div id="grid">..all kinds of things in here</div>
</div>

Answer

tw16 picture tw16 · Aug 24, 2011

The problem is caused by your #grid having a width:1140px.

You need to set a min-width:1140px on the body.

This will stop the body from getting smaller than the #grid. Remove width:100% as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/

html, body{
    margin:0;
    padding:0;
    min-width: 1140px; /* this is the important part*/
}
#grid-container{
    background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
    width:1140px;
    margin:0px auto;
}