CSS 定位 : Fixed and relative interchangeable regarding absolute?

标签 css

关于 absolute 定位,fixed 似乎像 relative 一样工作。

.fixed, .relative {
  border: 1px solid;
  width: 150px;
  height: 150px;
}

.fixed {
  border-color: red;
  position: fixed;
}

.relative {
  border-color: blue;
  margin-left: 200px;
  position: relative;
}

.absolute {
  background-color: rgba(0, 0, 0, 0.2);
  position: absolute;
}

.a {
  top: 0;
  left: 0;
}

.b {
  bottom: 0;
  right: 0;
}
<div class="fixed">
  <span class="absolute a">Left Top</span>
  <span class="absolute b">Right Bottom</span>
</div>

<div class="relative">
  <span class="absolute a">Left Top</span>
  <span class="absolute b">Right Bottom</span>
</div>

不幸的是,我不明白为什么。我希望这会在某处定义,但我只能找到讨论 absoluterelative 的资源,而不是 absolutefixed.

这引出了一个问题:关于 absolute 位置,我是否可以处理 fixedrelative 元素?同样,是否可以使用 top/left/right/bottom 来控制到父级的偏移量?

最佳答案

我认为除了 position:static 之外的任何东西都会为定位的 child 设置一个新的父上下文。

这可以在 MDN 文档中针对绝对定位 进行验证

The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).

因此设置 position:fixed 确实会导致绝对子元素跟随新上下文。

这个可以看出来fiddle here .更改 .rel div 的 position 会移动红色 div 的集合,但绝对定位的蓝色 div 会随之移动。

另一个很好的来源是 w3.org

An essential concept when it comes to absolute positioning is the containing block: the block box that the position and dimensions of the absolutely positioned box are relative to. For static boxes and relatively positioned boxes the containing block is the nearest block-level ancestor—the parent element in other words. For absolutely positioned elements however it’s a little more complicated. In this case the containing block is the nearest positioned ancestor. By “positioned” I mean an element whose position property is set to relative, absolute or fixed—in other words, anything except normal static elements.

来源: MDN Positon , w3org absolute position

关于CSS 定位 : Fixed and relative interchangeable regarding absolute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257964/

相关文章:

javascript - 如何分别为每张幻灯片制作标题动画

javascript - 使用 MUI 中的 Switch 在 useState 之间切换

html - 这个 css 选择器有缩写形式吗

悬停时带有 sprite 的 HTML/CSS 社交按钮

javascript - onsubmit validateForm 函数不起作用

html - 签名的语义 HTML 标记

html - 页面宽度超过浏览器窗口宽度。使用html和css

html - Internet Explorer 8 规模问题

php - 使用 imap 通过 php 打开电子邮件给我这个错误 Message : imap_open() [function. imap-open] : Couldn't open stream {imap. gmail.com:993/imap/ssl}INBOX

jQuery cycle.lite 插件 - 如何给包含 div 响应高度?