调整固定菜单和页面内容 CSS

Adjusting fixed menu and the content of a page with CSS

我有一个固定的菜单栏,因此当用户滚动时它会保留在页面顶部。

但是,我希望菜单和页面之间有一个间隙(下面称为 pageTest)。

我尝试将 .menu 中的边距更改为

margin: 0 0 50px; 0;

然而没有任何反应?我的 fiddle

HTML

<body>
<div class="menu">

</div>

<div class="content">

</div>

</body>

CSS

body {
padding: 0px;
margin: 0px;
}

.menu {  
  background-color: #9FACEC;    /* Medium blue */
  position: fixed;
  width: 100%;
  margin: 0;
  z-index: 1;
  display: flex; 
  justify-content: center;
  overflow: hidden;
  height: 100px;
}

.content {
 width: 90%;
 margin: 0 auto;
 overflow: hidden;
 background-color: yellow;
 height: 800px;
 }

您应该在菜单 div 中使用 top:0 并在你的情况下给出与 Nav 高度相同的边距是 100px 工作代码在这里

<body>


<div class="menu">

</div>

<div class="pageTest">


</div>

</body>

css 已编辑

    body {
    padding: 0px;
    margin: 0px;
}

.menu {  
  background-color: #9FACEC;    /* Medium blue */
  position: fixed;
  width: 100%;
  margin: 0;
  z-index: 1;
  display: flex; 
  justify-content: center;
  overflow: hidden;
  height: 100px;
  top:0;
}


.pageTest {
  width: 90%;
  margin: 0 auto;
  overflow: hidden;
  background-color: yellow;
  height: 800px;
  margin-top:150px
}

希望我回答了你的问题

position: fixed 从正常文档流中删除一个元素。在此元素上设置边距不会影响周围的元素。

您的保证金应添加到 .content 而不是 .menu

.menu 还需要 top: 0 来防止页边距将其推到页面下方。

body {
  padding: 0px;
  margin: 0px;
}

.menu {
  background-color: #9FACEC;
  /* Medium blue */
  position: fixed;
  width: 100%;
  margin: 0;
  z-index: 1;
  display: flex;
  justify-content: center;
  overflow: hidden;
  height: 100px;
  top: 0; /* Added */
}

.content {
  width: 90%;
  margin: 0 auto;
  margin-top: 55px;
  overflow: hidden;
  background-color: yellow;
  height: 800px;
  margin-top: 125px; /* Added */
}
<div class="menu">

</div>

<div class="content">


</div>


参见: Case where .pageTest is above .menu
As position:fixed on .menu div 从流中删除元素,并且 .pageTest div 然后进行相应调整,在这种情况下使其从文档的顶部位置开始。

所以,我们可以把position:relative.pageTestdiv来操纵top property .

.pageTest { //other css properties.. position: relative; top: 150px; }

提供 top:100px 将在 .menu div 之后启动 .pageTest div。
所以添加了50px来让两个div之间有一个空隙。

body {
    padding: 0px;
    margin: 0px;
}

.menu {  
  background-color: #9FACEC;    /* Medium blue */
  position: fixed;
  width: 100%;
  margin: 0;
  z-index: 1;
  display: flex; 
  justify-content: center;
  overflow: hidden;
  height: 100px;
}


.pageTest {
  width: 90%;
  margin: 0 auto;
  overflow: hidden;
  background-color: yellow;
  height: 800px;
  position: relative;
  top: 150px; // can be adjusted accordingly
}
<body>


<div class="menu">

</div>

<div class="pageTest">


</div>

</body>