Search code examples
csshtmlpositioning

CSS Positioning not displaying as expected


I thought I was getting the hang of CSS and had finally conquered positioning! Well I had until I tested my site locally on my ipad!

Using the below example I just want the background to be black (done no problem). On top of the black background I want the green "content-background" to run across the whole screen from left to right (100%) above the black background. On top of the green "content-background" I want the main-container div. I am not sure why but my example is not working? This should be a simple thing to do??? The problem is noticeable when the browser is shrunk from say right to left and then the scroll horizontal scroll bar is moved to the right. When this happens you will see that the green "content-background" does not expand vertically across the whole screen???

Any help is greatly appreciated : )

Fiddle: http://jsfiddle.net/Margate/Sk5X9/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
<title>Positioning</title>

<style type="text/css">     
#page-background{background-color:black; }  
#content-background{position:absolute; top: 100px; width: 100%; height: 616px; background-color: green;}
#main-container{position: relative; top: 0px; width: 1000px; height: 910px; margin: 0px auto; border: 1px solid red;}
</style>
</head>

<body id="page-background">

<div id="content-background"></div>
<div id="main-container">

</div>
</body>
</html>

Solution

  • I took your fiddle and fiddled with it a little bit to get the desired effect that you had mentioned.

    without modifying the HTML here is the new CSS

    #page-background {
        background-color:black;
        width: 100%;
    }
    #content-background {
    
        margin-top: 100px;
        width: 100%;
        height: 616px;
        background-color: green;
    }
    #main-container {
        position: absolute;
        top: 0px;
        width: 100%;
        height: 910px;
        margin: 0px auto;
        border: 1px solid red;
    }
    

    I find that specifying the body width to 100% gives the child divs a proper reference to the screen size and allows the child DIV ( content-background ) to span the length of the screen.

    ** because the DIV is no longer "absolute" positioned the top, left, bottom and right properties will do nothing. instead use margins to move stuff around.

    as for the border DIV -- because it is after the ( content-background ) Div -- putting this in relative positioning will place it after the ( content-background ) DIV -- by specifying this Div as "absolute" you can place it anywhere on the screen provided you set the top, left, bottom and right properties.

    I hope this helps guide you in the right direction for future css usage as there are about a million ways that this example can be written :)