【发布时间】:2014-11-18 03:35:07
【问题描述】:
我正在学习 CSS,并尝试创建一个简单的布局。
我将“标题”设置为 100% 的宽度,将“左侧”设置为 20% 的宽度,将“右侧”设置为 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”加上“right”在页面中占据较大的位置,而“header”占据较小的位置,因此它们的宽度相等。
另一个具有相同结果的解决方案是在“left: 0; right: 0; position: absolute;”的所有内容周围添加一个“容器” div。
我理解为什么这些解决方案使“左”加“右”更大(所以他们占据了整个页面),我不明白的是为什么“标题”突然变小了 .如果固定的“标题”超出常规流程,为什么更改正文的边距会影响它?
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>
谢谢
【问题讨论】:
-
margins - 默认情况下不包括在宽度计算中。例如一个盒子的全宽是leftmargin + leftpadding + box width + rightpadding + rightmargin。
-
@MarcB 这里没有边距吗?但这确实也是经典
-
总是有默认边距,除非您在某处使用 CSS 重置。
-
这个link 将帮助你更多地了解 CSS 盒子模型
-
感谢 cmets。我添加了边距:0;填充:0;边框:无;到 div 选择器,它仍然不起作用。
标签: html css layout width stylesheet