我正在学习CSS并尝试创建一个简单的布局。
我将"header"设置为100%的宽度,"left"设置为20%的宽度,"right"设置为80%的宽度。但是,"header"的宽度大于左侧和右侧的总宽度。为什么会这样,并该如何解决?
我将"header"设置为100%的宽度,"left"设置为20%的宽度,"right"设置为80%的宽度。但是,"header"的宽度大于左侧和右侧的总宽度。为什么会这样,并该如何解决?
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>
编辑
感谢您的回答以及一些阅读,我现在明白问题是主体部分的边距。当我使用body {margin:0;}时,“左”和“右”占据页面上更大的空间,“标题”占据较小的空间,因此它们的宽度相等。
另一种解决方案是在所有内容周围添加一个具有“left:0; right:0; position:absolute;”属性的“容器”div,带来相同的结果。
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>
谢谢