Home >Web Front-end >CSS Tutorial >Why Does Using 100vw Cause Horizontal Overflow with Multiple Elements?

Why Does Using 100vw Cause Horizontal Overflow with Multiple Elements?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 04:29:10677browse

Why Does Using 100vw Cause Horizontal Overflow with Multiple Elements?

Understanding Horizontal Overflow Caused by 100vw

When using 100vw to define the width of elements, developers may encounter unexpected horizontal overflow when multiple such elements are present. While 100vw is intended to signify "100% of the viewport width," certain scenarios can lead to this behavior.

Consider the following code:

html, body {margin: 0; padding: 0}
.box {width: 100vw; height: 100vh}

<div class="box">Screen 1</div>

This code will result in a single element that fills the entire screen without any scrollbars. However, if a second element is added:

<div class="box">Screen 1</div>
<div class="box">Screen 2</div>

The result is not only vertical scrollbars (as expected) but also a slight horizontal scroll. Why does this occur?

The reason lies in the presence of vertical scrollbars. When the content of the div elements exceeds their height, vertical scrollbars appear. This reduces the available horizontal space for the elements, causing them to overflow horizontally.

To resolve this issue, one can add max-width: 100%; to the box class:

.box {
    width: 100vw;
    height: 100vh;
    max-width: 100%;
}

By limiting the element's maximum width to 100%, the horizontal overflow is prevented even when vertical scrollbars are present.

The above is the detailed content of Why Does Using 100vw Cause Horizontal Overflow with Multiple Elements?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn