Prevent 100vw from creating horizontal scroll

2019-01-17 14:47发布

If an element is set to width: 100vw; and there is a vertical scrollbar the width of the element will be equal to the viewport plus the width of the scrollbar.

Is it possible to prevent this?

Is it possible to prevent this without disabling horizontal scrolling on the entire page? Aside from changing my css/markup to make the element 100% of the body width I can't think of anything.

Tested in Chrome Version 43.0.2357.81 m & FF 36.0.1 & Opera 20.0.1387.91 on Windows 8.1

Here is the code as requested:

Example

html

<div class="parent">
    <div class="box"></div>
</div>
<div class="tall"></div>

css

body { margin: 0; }
html { box-sizing: border-box; }
*, *::before, *::after {
    box-sizing: inherit;
    position: relative;
}
.parent {
    background: rgba(0, 0, 0, .4);
    height: 100px;
    width: 5rem;
    margin-bottom: 25px;
}

.box {
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, .4);
    height: 50px;
    width: 100vw;
}

.tall {
    height: 100rem;
}

标签: css css3 scroll
8条回答
不美不萌又怎样
2楼-- · 2019-01-17 15:22

I fixed this on my site by adding body{overflow-x:hidden} to the page in question.

Works on your example too.

查看更多
Evening l夕情丶
3楼-- · 2019-01-17 15:24

An element with width: 100vw only causes horizontal scrollbars when one of it's parents has a horizontal padding. Otherwise it should fit in well.

Check this fiddle: http://jsfiddle.net/1jh1cybc/ The .parent2 has a padding, which causes the inner .box to break out of it's parent width.

Edit:

In your case I guess your body has a margin. Check this fiddle out with you code and try to remove the body css rule: http://jsfiddle.net/1jh1cybc/1/

查看更多
登录 后发表回答