Prevent 100vw from creating horizontal scroll

前端 未结 11 2083
不知归路
不知归路 2020-12-04 19:13

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.<

11条回答
  •  长情又很酷
    2020-12-04 19:46

    Paddings and borders can interfere. So can margin. Use box-sizing to calculate width including these attributes. And maybe remove margin (if any) from the width.

    * {
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    body {
        margin: 0; /* interferes with 100vw */
    }
    .parent {
        width: 100vw;
        max-width: 100%; /* see below */
    }
    .box {
        width: 100%; /* For those good old-fashioned browsers with no vw or calc() support */
        width: -webkit-calc(100vw - [your horizontal margin, if any]);
        width: -moz-calc(100vw - [your horizontal margin, if any]);
        width: calc(100vw - [your horizontal margin, if any]);
        max-width: 100%
    }
    

    It seems you have to add max-width: 100%; if there is a reflow which is causing the scrollbar to appear after the initial viewport width calculation. This does not seem to happen in browsers without an interfering scrollbar (iOS, OS X, IE 11 Metro), but can affect all other browsers.

提交回复
热议问题