gpt4 book ai didi

html - 制作一个固定在屏幕顶部的相对div

转载 作者:行者123 更新时间:2023-11-28 10:38:42 25 4
gpt4 key购买 nike

我需要让 #outer1 固定在屏幕顶部,但我无法在不弄乱当前位置的情况下做到这一点。我不能只固定 #outer1,因为我需要它是相对的,因为里面的 div 需要绝对定位。我应该怎么做才能使 #outer1 固定在屏幕顶部?

div {
border: 1px solid black;
}
#outer1 {
height: 100px;
position: relative;
}
#outer2 {
height: 900px;
}
#left {
display: inline-block;
}
#right {
display: inline-block;
position: absolute;
right: 0;
}
<div id='outer1'>
<div id='left'>Left</div>
<div id='right'>Right</div>
</div>

<div id='outer2'></div>

最佳答案

I cannot just make #outer fixed, as I need it to be relative, because the divs on the insides need to be absolute positioned.

仅仅因为绝对定位的子级最常见的安排涉及相对定位的父级,并不意味着这是唯一的方式。

绝对定位元素的规则是它们的包含 block 是 nearest positioned ancestor .位置固定的 #outer1 是定位的祖先,因此它符合条件。只是人们在 99% 的时间里都使用 position: relative,因为这对父级的影响微乎其微。

使用 position: fixed 作为绝对定位子元素的包含 block 没有问题。

来自 MDN:

A positioned element is an element whose computed position property is either relative, absolute, fixed or sticky. (In other words, anything other than static)

A relatively positioned element is an element whose computed position property is relative.

An absolutely positioned element is an element whose computed position property is absolute or fixed.

A stickily positioned element is an element whose computed position property is sticky.

The top, right, bottom, and left properties specify the position of positioned elements.

The absolutely positioned element is positioned relative to nearest positioned ancestor (non static). If a positioned ancestor doesn't exist, the initial container is used.

source: https://developer.mozilla.org/en-US/docs/Web/CSS/position

关于html - 制作一个固定在屏幕顶部的相对div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com