如何在div标签之间形成垂直空间?

Siv*_*ash 6 html css html5 css-position css3

我有三个div标签,我想在div标签之间垂直留出空间,也希望将我的第一个div标签作为固定的。

当我将第一个div位置设置为非固定位置时,我可以留出垂直空间。

<html>
<head>
<title>div</title>
</head>
<body style="margin: 0; padding: 0;">
<div style="width:100%; background-color:Lime;">
<div style="width:100%; height:10%; background-color:Blue;">
a
</div>
<div style="width:70%; height:100%; background-color:Gray; margin: auto; margin-top: 2em; margin-bottom: 2em;">
b
</div>
<div style="width:100%; height:5%; background-color:Aqua;">
c
</div>        
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当我将“ div a”的位置更改为固定值时,“ div a”和“ div b”都从空白处下降:2em。

<html>
<head>
<title>div</title>
</head>
<body style="margin: 0; padding: 0;">
<div style="width:100%; background-color:Lime;">
<div style="width:100%; height:10%; background-color:Blue; position: fixed;">
a
</div>
<div style="width:70%; height:100%; background-color:Gray; margin: auto; margin-top: 2em; margin-bottom: 2em;">
b
</div>
<div style="width:100%; height:5%; background-color:Aqua;">
c
</div>        
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

请帮助我将“ div a”设置为固定,并在“ div a和b”之间留出空间。

sea*_*win 5

为了将div.a(固定的)保持在页面顶部,添加top: 0;,如果您希望它保持在其余内容的顶部,请包含z-index: 2;.

为了增加div.a和之间的间距,div.b您将不得不在div周围放置一个容器div.b并对其进行适当的填充。如果您只是将 padding 放在主容器 div 上,它将偏移div.a。

如果可能,将确定的高度设置为div.a,而不是百分比,因为这将使div.b和容器的垂直对齐更加容易。这样,你可以设置margin-top为div.b是height的div.a。

下面是为了更好的可读性而重构的 CSS 和 HTML:

/* CSS */
* {
  margin: 0;
  padding: 0;
}
div {
  width: 100%;
}
div.container {
  height: 100%;
}
div.container,
div.b-container {
  background-color: lime;
}
div.a {
  height: 70px;
  background-color: blue;
  position: fixed;
  top: 0;
  z-index: 2;
}
div.b-container {
  position: relative;
  padding-top: 2em;
  margin-top: 70px;
}
div.b-container div.b {
  width: 70%;
  height: 100%;
  background-color: gray;
  margin: auto;
  
  margin-bottom: 2em;
}
div.c {
  height: 5%;
  background-color: aqua;
}
Run Code Online (Sandbox Code Playgroud)
<!-- HTML -->
<div class="container">
  <div class="a">
    a
  </div>
  <div class="b-container">
    <div class="b">b
    </div>
  </div>
  <div class="c">
    c
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)