gpt4 book ai didi

html - 确保相对定位的元素留在顶部容器内

转载 作者:太空宇宙 更新时间:2023-11-04 09:28:42 26 4
gpt4 key购买 nike

相对和绝对定位是很棒的工具,但它们将元素从流中移除,这导致它们的使用受到一些限制。我想我只是遇到了其中一个,但我希望有人能证明我错了。

明确说明:我有一个相对于其父级定位的 div。问题是,在某些情况下,这个流外元素可以比顶部元素(例如主体)走得更远,并添加一个水平滚动条。演示如下:

.top-container {
width: 80%;
height: 100px;
margin: auto;
border: dashed 2px red;
}
.container {
width: 80%;
height: 50px;
margin: 25px auto;
border: dotted 1px blue;

position: relative;
}
.absolute {
width: 100%;
background-color: black;
color: white;

position: absolute;
top: 30%;
right: -50%;
}
<div class="top-container">
<div class="container">
<div class="absolute">
absolutely
</div>
</div>
</div>

我的问题是:有没有办法告诉 CSS 绝对定位的元素不应该比 .top-container 的边界更左或更右?表现得像一种 max-left/max-right

(例如,在我的示例中,移动黑色 div,使其不会超出红色虚线)

最佳答案

如果您决定将元素定位在精确 位置 - 您不能说您希望将它定位在某处。您可以使用右/左边距(或百分比位置)。

另一种选择是使用 overflow 选项在容器上设置滚动条(或者指定如果元素离开容器则应该隐藏它):

.top-container {
width: 80%;
height: 100px;
margin: auto;
border: dashed 2px red;
}
.container {
width: 80%;
height: 50px;
margin: 25px auto;
border: dotted 1px blue;

position: relative;
overflow: auto;
}
.hidden-overflow {
overflow: hidden;
}
.absolute {
width: 100%;
background-color: black;
color: white;

position: absolute;
top: 30%;
right: -50%;
}
<div class="top-container">
<div class="container">
<div class="absolute">
absolutely
</div>
</div>
</div>

<div class="top-container">
<div class="container hidden-overflow">
<div class="absolute">
absolutely
</div>
</div>
</div>

关于html - 确保相对定位的元素留在顶部容器内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40932750/

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