【发布时间】:2016-08-05 20:58:39
【问题描述】:
有时在按宽度包裹的 div 中需要将元素背景设置为全宽,所以我将其设置为伪元素,但桌面浏览器,当页面长时,垂直滚动条向视口增加 16px,所以我计算一下 通过计算(见下文)。
这里是Example
HTML:
<div class="wrapped">
<h1>100vw background in wrapped</h1>
<div class="fullbg">
some body text, images, etc here
</div>
</div>
CSS
html, body { margin: 0; padding: 0; }
body { height: 100%; width: 100%; }
div { position: relative; }
*,*:before,*:after { box-sizing: border-box;
-moz-box-sizing: border-box; -webkit-box-sizing: border-box;
}
.wrapped {
width: 70%;
margin: 0 auto;
height: 150vh; /* simulate long heigh */
}
.fullbg {
height: 5em;
/* some styles here*/
}
.fullbg:before {
content: "";
bottom: 0;
display: block;
background: rgba(85, 144, 169, 0.7);
position: absolute;
width: 100vw;
right: 50%;
margin-right: -50vw; /* work for short page or mobile browser*/
margin-right: calc( -50vw + 8px ); /* work for desctop long page */
top: 0;
z-index: -1;
}
我看了答案
和其他问题, 但没有找到真正真正的通用 css 解决方案
作为一个临时解决方案可能是一个js,比如this:
var scrollbarWidth = ($(document).width() - window.innerWidth);
但我认为这不是最好的解决方案,考虑到滚动宽度可能会有所不同,现在我不知道如何将它与伪一起使用。
ps。没有人溢出:隐藏!
【问题讨论】:
-
好问题。我认为“cssfix”通过使宽度允许垂直滚动条的宽度来解决问题,但当然 8px 不足以实现这一点!让我们看看你得到了什么答案。
标签: css width scrollbar viewport