.parent {
width: 300px;
height: 300px;
background: red;
position: relative;
}
.child-green {
position: absolute;
top: 10px;
left: 250px;
width: 100px;
height: 100px;
background: green;
}
.child-blue {
background: blue;
margin: 5px;
width: 100px;
height: 500px;
}
<div class='parent'>
<div class='child-green'></div>
<div class='child-blue'></div>
</div>
代码示例:https://codepen.io/asad111/pen/jOPqpaj
所有元素都必须在此位置,但是绿色元素没有水平滚动条(当然,不能只是隐藏溢出x或类似的技巧)
我不能从父级获取overflow: auto
,否则它将不会滚动该流中的元素。例如,蓝色框需要强制父级滚动。
[注:我真的需要孩子超越父母界限我正在制作动画,动画在屏幕上移动,并且需要边缘到边缘。
所以问题是,为什么定位绝对元素而不应该占用空间...好,需要空间?我该如何解决?
一种解决方法是重新包装:
https://codepen.io/asad111/pen/jOPqvYV
.parent {
width: 300px;
height: 300px;
background: red;
position: relative;
overflow: auto;
}
.child-wrapper {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
.child-green {
position: absolute;
top: 10px;
left: 250px;
width: 100px;
height: 100px;
background: green;
}
.child-blue {
background: blue;
margin: 5px;
width: 100px;
height: 500px;
}
<div class='parent'>
<div class='child-wrapper'>
<div class='child-green'></div>
</div>
<div class='child-blue'></div>
</div>
还有其他想法吗?
子元素的左边为250px +宽度为100px,所以父元素中总共有350px,宽度为300px,这就是为什么它显示滚动条的原因。将其设置为200px,然后滚动条将消失。
尝试此代码
.child {
position: absolute;
top: 10px;
left: 0;
width: 100px;
height: 100px;
background: green;
}