代码及运行效果也可在 JS Bin 中查看:
https://jsbin.com/nolatakoto/edit?html,css,output
主要有两个疑问:
1、给位于文档流中的.main 元素添加 margin-top 属性,
但为什么.main-header 元素看起来似乎也同时受到了 margin-top 属性的作用?
2、如果给 body 元素添加上 border 属性,此时.main-header 元素将回到设想中的位置,
为什么给 body 元素加上 border 属性就会发生这种变化呢?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="main-header">Header</div>
<div class="main">Main</div>
</body>
</html>
body {
margin: 0;
/*border: 2px solid red;*/
}
.main-header {
position: absolute;
background: #ccc;
}
.main {
font-size: 50px;
margin-top: 50px;
background: blue;
}
1、关于 css top 属性 属性上说明。
对于绝对定位元素,如果
top
或bottom
上都没有设置,即默认auto
,则元素的垂直位置就是它假如作为静态(即static)元素时该在的位置,虽然脱离文档流。2、至于为什么
border
会有这种现象,其实这是典型的 外边距重叠 问题中的没有内容将父元素和后代元素分开的情况。详情查看该文档,其实设置
padding
不为零等都能实现同样效果。