Div 个元素没有正确定位

Div elements not positioning properly

我正在使用 2 个 div 元素。这些元素相互重叠,但我希望它们一个接一个地跟随。

 <!DOCTYPE>
    <html>
    <head>
    <title>Online</title>
    <style>
    .rectangle {
     min-height: 40px;
     margin-bottom: 20px;
     border: 1px solid transparent;
     height: 65px;
     position: fixed;
     top: 0px;
     right: 0px;
     left: 0px;
     border-radius: 0px;
     background-color:#67518e;
     z-index:15;
     
    }
    .section-content {
        padding-top: 30px;
        padding-bottom: 30px;
        border-top: 1px solid green;
        border-bottom: 1px solid green;
     position: absolute;
     right: 0; 
     left: 0;
     z-index: 10;
     background-color: yellow;
     }
    </style>
    </head>
    <body>
     <div class="rectangle"> 
     </div> 
    <div class="section-content">
    </div>

发生这种情况是因为您正在对具有 class .rectangle 的元素使用 position: fixed。一种不改变位置的解决方案是对元素 .section-content:

使用 margin-top: 59px

.rectangle {
  min-height: 40px;
  margin-bottom: 20px;
  border: 1px solid transparent;
  height: 65px;
  position: fixed;
  top: 0px;
  right: 0px;
  left: 0px;
  border-radius: 0px;
  background-color: #67518e;
  z-index: 15;
}
.section-content {
  padding-top: 30px;
  padding-bottom: 30px;
  border-top: 1px solid green;
  border-bottom: 1px solid green;
  position: absolute;
  right: 0;
  left: 0;
  z-index: 10;
  background-color: yellow;
  margin-top: 59px;
}
<div class="rectangle"></div>
<div class="section-content">

关于职位的documentation你可以仔细看看

您可以同时制作 <div>s <span>s,或者同时制作 CSS 类,添加以下行:display: inline;.

删除定位声明,因为这会导致您的问题:(我还删除了一些未使用的 'other' css)。

因为 Position:absolute;

align itself to its nearest ancestor with a relative height

重要的是要知道,由于您的第一个 div 具有 'fixed' 位置,因此它将自身对齐到页面的左上角。


为了使页面的 divs "fill the width",我包含了一个 "simple css reset",包括:

html,body{
  margin:0;
  padding:0;
  }

在我的 css


html,
body {
  margin: 0;
  padding: 0;
}
.rectangle {
  height: 65px;
  background-color: #67518e;
  width: 100%;
}
.section-content {
  padding-top: 30px;
  padding-bottom: 30px;
  border-top: 1px solid green;
  border-bottom: 1px solid green;
  background-color: yellow;
  width: 100%;
}
<div class="rectangle">
</div>
<div class="section-content">
</div>

附带说明:我想强调一下您对

的使用
  min-height: 40px;

这永远不会被使用,因为您使用的是固定高度。只有当您使用百分比之类的度量单位而不是 px(因为它们不会动态更改)时,这种样式才会真正发挥作用


LIVE DEMO OF STICKY HEADER