Search code examples
htmlcsswidthdimension

Why width: 100% is not assuming the full window width size?


I have HTML code and CSS below:

body{
	background-color: #C7C7C7;
}
#content{
	background-color: #FFF;
	text-align: center;
}
.warp{
	padding:15px;
	display: inline-block;
	width: 700px;
	background-color: red;
}
#header{
	width: 100%;
	background-color: #000;
	color: #FFF;
}
<body>
<div id="header">
	HEADER IS HERE
</div>
<div id="content">
	<div class="warp">
		CONTENT IS HERE
	</div>
</div>
</body>

But when I resize my browser, a header div not width: 100%

You can see that in this image: enter image description here

How to fix it?

Thanks you so much.


Solution

  • It is because when you resize the browser there's a fixed width div i.e. .wrap div to 700px and if you resize the browser the window width is upto 700px but 100% width is applied to the view-port width.

    So, how you can do is to apply max-width to the .wrap div:

    .warp{
        padding:15px;
        display: inline-block;
        width: 700px;
        max-width: 100%;
        box-sizing: border-box;/*for padding values*/
        background-color: red;
    }
    

    So, in smaller window .wrap div won't go beyond the 100% view-port width and your header would be in corresponding with that and in larger window the .wrap div won't go beyond the 700px as what you want.


    Here's the demo:

    body{
    	background-color: #C7C7C7;
    }
    #content{
    	background-color: #FFF;
    	text-align: center;
    }
    .warp{
    	padding:15px;
    	display: inline-block;
    	width: 700px;
        max-width: 100%;
        box-sizing: border-box;
    	background-color: red;
    }
    #header{
    	width: 100%;
    	background-color: #000;
    	color: #FFF;
    }
    <body>
    <div id="header">
    	HEADER IS HERE
    </div>
    <div id="content">
    	<div class="warp">
    		CONTENT IS HERE
    	</div>
    </div>
    </body>