【问题标题】:css position fixed is taking the margin of the other div [duplicate]固定的css位置正在占用另一个div的边距[重复]
【发布时间】:2020-07-27 16:52:39
【问题描述】:

body {
  background-color:whitesmoke
}

.fixed {
  background-color:gray;
  position: fixed;
}
<body>
  <div class="fixed">
    <h1>header data</h1>
  </div>
    <div style="margin-top: 60px;">
      <h1>hello how are you</h1>
  </div>
</body>

我的正文中有这段代码,正文中有第一个 div,它有固定的位置,但它从顶部开始给出第二个 div 中给出的边距 60。由于固定位置总是相对于文档占据位置,那么为什么它会占据第二个 div 的边距。

【问题讨论】:

标签: html css


【解决方案1】:

只需指定固定div 的位置,否则会(错误地)推断。 添加top: 0 会将固定的 div 设置为屏幕顶部。

 <div style=" position: fixed; background-color: aqua; top: 0;">
     <h1 >header data</h1>
 </div>
 <div style="background-color: aliceblue;">
     <div style="margin-top: 60px;">
         <h1>hello how are you</h1>
     </div>
 </div>

编辑 如文档中所述(加粗):

元素从正常的文档流中移除,并且没有为页面布局中的元素创建空间。它相对于视口建立的初始包含块定位,除非它的祖先之一的变换、透视或过滤器属性设置为非无 [...]

正如 CBroe 指出的,对于 margin collapsing

如果没有边框、内边距、内联内容、高度或最小高度将块的上边距与其下边距分开,则其上边距和下边距折叠。 p>

您可以看到这两个 sn-ps 之间的区别:第一个创建一个包含固定元素的非空 1px 块,而另一个创建一个空块,导致边距折叠。

<div style="display: block; height: 1px;">
<div style=" position: fixed; background-color: aqua;">
     <h1 >header data</h1>
 </div>
 </div>
 <div style="margin-top: 60px; background-color: aliceblue;">
     <h1>hello how are you</h1>
 </div>

另一种解决方案是使用 padding 而不是 margin,以避免折叠触发:

<div style="display: block; height: 0px;">
<div style=" position: fixed; background-color: aqua;">
     <h1 >header data</h1>
 </div>
 </div>
 <div style="margin-top: 60px; background-color: aliceblue;">
     <h1>hello how are you</h1>
 </div>

<div style=" position: fixed; background-color: aqua;">
     <h1 >header data</h1>
 </div>
 <div style=" padding-top: 60px;">
     <div style="background-color: aliceblue;">
         <h1>hello how are you</h1>
     </div>
 </div>

【讨论】:

  • 我知道添加前 0 会做到这一点。但我想知道它占用子 div 的边距的原因。
猜你喜欢
  • 1970-01-01
  • 2019-08-30
  • 1970-01-01
  • 2014-03-31
  • 2020-11-22
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
相关资源
最近更新 更多