Div with width 100% and margins or padding gets wider than 100% [solved]
If a div is set to width (or height) 100% and margins or padding are added, it will be wider than 100% causing the scrollbars to appear in the browser.
For example like this (click here to view live sample):
<html>
<head>
<style type="text/css">
body, html {
width: 100%;
border: 0;
margin: 0;
padding: 0;
}
#wrapper {
width: 100%;
margin: 0;
padding: 0;
border: 0;
}
#container {
width: 100%;
margin: 10px;
padding: 0;
border: 0;
background-color: lightblue;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="container">
<h1>Div taking more than 100% space</h1>
<p>It demonstrates a div that is taking up more than 100%. Notice the horizontal scroll bar below.</p>
</div>
</div>
</body>
</html>
The solution is to set the inner container width to auto instead of 100%, like this (click here to view live sample):
<html>
<head>
<style type="text/css">
body, html {
width: 100%;
border: 0;
margin: 0;
padding: 0;
}
#wrapper {
width: 100%;
margin: 0;
padding: 0;
border: 0;
}
#container {
width: auto;
margin: 10px;
padding: 0;
border: 0;
background-color: lightblue;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="container">
<h1>Div NOT taking more than 100% space</h1>
<p>It demonstrates a div that is NOT taking up more than 100%. Notice the absence of the horizontal scroll bar below.</p>
<p>The difference/solution is to set the inner div with width: auto.</p>
</div>
</div>
</body>
</html>
Leave a Reply
Want to join the discussion?Feel free to contribute!