相对和绝对定位是很棒的工具,但它们将元素从流中移除,这导致它们的使用受到一些限制。我想我只是遇到了其中一个,但我希望有人能证明我错了。
明确说明:我有一个相对于其父级定位的 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/