Marcus Marcus - 6 days ago 6
CSS Question

How do I get a div to fit to the screen with no overflow in CSS

#topnavbar {
width:100%;
padding:0;
border:1px solid gray;
margin:0; }

#topnavbar p {
margin:0; }

body {
margin-left:auto;
margin-right:auto;
margin-top:0;
width:1024px; }


That is my code. How do I get it to have the bar(which is named topnavbar) to fit the whole screen without overflowing? And I don't want to do
overflow:hide;
or whatever.

Answer

Your css is a little off:

#topnavbar {
   width:100%;
   padding:0;
   border:1px solid gray;
   margin:0; 
}

#topnavbar p {
   margin:0; 
}

#container{
    width:1024px;
    margin: 0 auto;
}

body {
   /* you do not need any of your css here */
}

html:

<body>
    <div id="topnavbar">
        <p>Some text</p>
    </div>
    <div id="container">
        whatever you want to center
    </div>
</body>

the basic idea is to width 100% an element who does not have a parent and then apply your centering container beneath it. In this case, #container.

Your css was applying a width to the body and therefore it was likely messing up your whole layout.

Comments