I'm learning CSS and I tried to create a simple layout.
I set the "header" to have a width of 100%, the "left" to have a width of 20% and the "right" 80%. But the width of the header is greater than the total width of the left and the right. Why is that and how to fix it?
div {
border-radius: 10px;
}
#header {
z-index: 1;
background-color: #80B7ED;
height: 50px;
width: 100%;
position: fixed;
}
.left {
background-color: #5A9DE0;
height: 400px;
width: 20%;
float: left;
position: relative;
}
.right {
background-color: #BFD9F2;
height: 400px;
width: 80%;
float: right;
position: relative;
}
#footer {
background-color: #80B7ED;
clear: both;
height:70px;
}
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title></title>
</head>
<body>
<div id="header">
</div>
<div class="left">
</div>
<div class="right">
</div>
<div id="footer">
</div>
</body>
</html>
Edit
Thanks to your answers and to some reading I get now that the problem is the margin of the body section. When I use body {margin: 0;} the "left" plus the "right" take a bigger place in the page and the "header" takes a smaller place, so their widths are equal.
Another solution with the same result is adding a "container" div around everything with "left: 0; right: 0; position: absolute;".
I understand why these solutions make the "left" plus the "right" bigger (so they take the whole page), what I don't get is why the "header" is suddenly smaller. If the fixed "header" is out of the regular flow, why changing the margin of the body influeces it?
body {
margin: 0;
}
div {
border-radius: 10px;
}
#header {
z-index: 1;
background-color: #80B7ED;
border-top-left-radius: 0;
border-top-right-radius: 0;
top: 0;
height: 50px;
width: 100%;
position: fixed;
}
.left {
background-color: #5A9DE0;
height: 400px;
width: 20%;
float: left;
position: relative;
}
.right {
background-color: #BFD9F2;
height: 400px;
width: 80%;
float: right;
position: relative;
}
#footer {
background-color: #80B7ED;
clear: both;
height:70px;
}
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title></title>
</head>
<body>
<div id="header">
</div>
<div class="left">
</div>
<div class="right">
</div>
<div id="footer">
</div>
</body>
</html>
Thanks
When using percentage widths the margin
, padding
and border
are not included in the calculation. So you want to be sure all of those are set to 0 on the corresponding elements.
margin: 0;
padding: 0;
border: none;
Alternatively, you could use the box-sizing
property which will make the calculation include padding
and border
. Then you would only have to account for the margins elsewhere.
box-sizing: border-box;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With