我已经定位了<div id="title">
在其原始位置上方 50px,div 的高度为 70px。我不明白为什么<div id="page1">
不是在标题 div 之后开始,而是仅在其原始高度 70px 之后开始。
我该如何纠正它?
* {
margin: 0;
padding: 0;
}
#title {
position: relative;
top: -50px;
width: 100%;
height: 70px;
background-color: blue;
}
#page1 {
background-color: lightgreen;
text-align: center;
position: relative;
z-index: 0;
width: 100%;
height: 500px;
}
#page1 img {
position: absolute;
top: 200px;
left: 50px;
width: 200px;
}
#page1 h1 {
padding-top: 100px;
}
#page2 {
background-color: red;
position: relative;
z-index: 1;
width: 100%;
height:800px;
}
<html>
<head>
<link rel = "stylesheet" href = "style.css">
</head>
<body>
<div id = "title"></div>
<div id = "page1"><h1>Hello !!!</h1><img src = "https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg"></div>
<div id = "page2"><div>
<script src = "script.js"></script>
</body>
</html>
最佳答案
使用相对位置和顶部属性是这里的问题。
通过声明 top: -50px,div 在视觉上从其原始位置移动,但 div 仍保留其在文档流中的原始位置
您可以使用 margin-top -50px 而不仅仅是顶部。这将移动整个 div 并保留 div 之间的间距。
有关“top”属性的说明,请参阅下面的文档。 https://developer.mozilla.org/en/docs/Web/CSS/top
长话短说
For relatively positioned elements (those with position: relative) the value specified will move the element below or above its position in the normal flow if it wasn't positioned.
关于css - 为什么 div 没有在前一个 div 之后立即堆叠? (不是 margin /填充问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38095673/