如何解决绝对定位的元素与屏幕的右侧重叠,没有滚动
我试图绝对定位高度和宽度未知的div
,以使其部分位于屏幕右侧,同时禁止向右滚动。当我尝试在屏幕的左侧执行此操作时,它的工作正常。但是,当我在屏幕右侧尝试操作时,出现了问题。
我尝试使用overflow-x
解决此问题,但这会使整个div
意外消失。
.parent1 {
position: relative;
background-color: #ddd;
}
.child1 {
position: absolute;
width: 100px;
height: 100px;
background-color: #00ff00;
left: -50px;
top: 0;
}
.parent2 {
position: relative;
background-color: #ddd;
}
.child2 {
position: absolute;
width: 100px;
height: 100px;
background-color: #ff0000;
right: -50px;
top: 0;
}
.parent3 {
position: relative;
background-color: #ddd;
overflow-x: hidden;
}
.child3 {
position: absolute;
width: 100px;
height: 100px;
background-color: #ff0000;
right: -50px;
top: 0;
}
<div class="parent1">
<div class="child1">
This works on the left: half of the DIV is off the screen and un-scrollable; the other half is showing.
</div>
</div>
<div class="parent2">
<div class="child2">
But when I try it on the right,I'm able to scroll the screen right and see this whole DIV.
</div>
</div>
<div class="parent3">
<div class="child3">
I would expect overflow-x to solve this problem,but it hides the DIV entirely.
</div>
</div>
在禁用滚动的情况下,如何使我的div
位于屏幕的右侧?
解决方法
您只需要在overflow-x: hidden
上应用body
。如果父项本身是可滚动的,则为overflow-x
隐藏parent
的解决方案将起作用,否则就没有什么可隐藏的。
body {
overflow-x: hidden;
}
.parent1 {
position: relative;
background-color: #ddd;
}
.child1 {
position: absolute;
width: 100px;
height: 100px;
background-color: #00ff00;
left: -50px;
top: 0;
}
.parent2 {
position: relative;
background-color: #ddd;
}
.child2 {
position: absolute;
width: 100px;
height: 100px;
background-color: #ff0000;
right: -50px;
top: 0;
}
.parent3 {
position: relative;
background-color: #ddd;
}
.child3 {
position: absolute;
width: 100px;
height: 100px;
background-color: #ff0000;
right: -50px;
top: 0;
}
<div class="parent1">
<div class="child1">
This works on the left: half of the DIV is off the screen and un-scrollable; the other half is showing.
</div>
</div>
<div class="parent2">
<div class="child2">
But when I try it on the right,I'm able to scroll the screen right and see this whole DIV.
</div>
</div>
<div class="parent3">
<div class="child3">
I would expect overflow-x to solve this problem,but it hides the DIV entirely.
</div>
</div>
,
将子级2的样式更改为position: fixed
.child2 {
position: fixed;
width: 100px;
height: 100px;
background-color: #ff0000;
right: -50px;
top: 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。