草庐IT

html - 为什么位置为 : fixed moving with a non-positioned sibling? 的元素

coder 2023-08-02 原文

关于 S.O. 有很多问题。涵盖了如何解决此问题的答案(添加 top: 0),但它们都没有尝试真正解释 header 移动背后的原因。我更好奇为什么会这样。

<header>Project Header</header> 
<main class="container" id="layout-mainContent">
    <div class="row" id="first-row">somecontent</div>
</main>

header {
   position: fixed;
}

#layout-maincontent {
   margin-top: 90px;  //moves header down.
}

类似问题列表,但没有推理:

  1. Topmost 'fixed' position div moving with non position div
  2. margin affects other fixed elements position
  3. margin-top div causes fixed header div to move down

似乎有理由认为固定标题粘在浏览器窗口的顶部并且不应移动,因为另一个非定位、非子、非父 div(也称为兄弟)。特别是因为固定标题在正常文档流之外。 MDN on Fixed Positioning

假设: 混淆源于固定元素相对于浏览器窗口的想法。这是事实,但是是使用视口(viewport)计算的。视口(viewport)是使用常规文档流中的元素计算的。因为文档流中的第一个 div 是非标题 div,所以视口(viewport)在应用 margin-top 之后开始。这只是猜测,我很乐意看到有人证实或纠正我。

最佳答案

使用 position: fixed,您的 header 元素将从文档流中移除。

第一个流入元素是 main,它在您的代码中有 margin-top: 90px

这个元素的父元素是 body,它通常有一个默认的 margin: 8px(参见 HTML default style sheet)。

由于 CSS margin collapsingbody 元素的 margin-top: 8pxmain 元素的 margin-top: 90px 折叠。

因此,现在具有相同边距的两个元素都向下移动了 90 像素。

html {
    background-color: green;
    height: 100%;
 }

body {
    background-color: pink;
    height: 100%;
}

header {
   position: fixed;
   border: 1px solid red;
}

main {
  margin-top: 90px;
  background-color:yellow;
}
<header>Project Header</header> 
<main class="container" id="layout-mainContent">
    <div class="row" id="first-row">somecontent</div>
</main>

jsFiddle

固定表头移动的原因如下:

  • 尽管 containing block 对于具有 position: fixed 的元素是视口(viewport)...
  • CSS 偏移属性(topbottomleftright)的初始值为 auto,如果元素在文档流中,它会将元素保持在正常位置。
  • 换句话说,当您将元素设置为 position: absoluteposition: fixed(position: absolute 的另一种形式)时,您正在指定所需的定位类型...但您并未将其定位在任何地方。
  • 直到您定义了元素实际定位的偏移量。
  • 要将标题移动到视口(viewport)的顶部,请使用 top: 0

html {
    background-color: green;
    height: 100%;
 }

body {
    background-color: pink;
    height: 100%;
}

header {
   position: fixed;
   border: 1px solid red;
   top: 0px; /* NEW */
}

main {
  margin-top: 90px;
  background-color:yellow;
}
<header>Project Header</header> 
<main class="container" id="layout-mainContent">
    <div class="row" id="first-row">somecontent</div>
</main>

jsFiddle

关于html - 为什么位置为 : fixed moving with a non-positioned sibling? 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38679945/

有关html - 为什么位置为 : fixed moving with a non-positioned sibling? 的元素的更多相关文章

随机推荐