CSS overflow

The overflow property in CSS specifies what should happen if content overflows an element’s box. It is used to control the behavior of content that is too large to fit in an element’s box.

overflow property values

1. visible: The default value. Content is not clipped and may render outside the element’s box.

2. hidden: Content that overflows the element’s box is clipped, and no scrollbars are provided.

3. scroll: Content that overflows the element’s box is clipped, but scrollbars are provided to allow the user to scroll to see the rest of the content.

4. auto: If the content overflows, the browser will display scrollbars only when necessary.

Syntax:


selector {
    overflow: visible | hidden | scroll | auto;
}

Example:-


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .box {
            width: 200px;
            height: 100px;
            border: 1px solid black;
            margin-bottom: 20px;
        }

        .visible {
            overflow: visible;
            background-color: lightblue;
        }

        .hidden {
            overflow: hidden;
            background-color: lightcoral;
        }

        .scroll {
            overflow: scroll;
            background-color: lightgreen;
        }

        .auto {
            overflow: auto;
            background-color: lightyellow;
        }

        .content {
            width: 300px;
            height: 150px;
            background-color: rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>

    <div class="box visible">
        <div class="content">This box has overflow: visible.</div>
    </div>

    <div class="box hidden">
        <div class="content">This box has overflow: hidden.</div>
    </div>

    <div class="box scroll">
        <div class="content">This box has overflow: scroll.</div>
    </div>

    <div class="box auto">
        <div class="content">This box has overflow: auto.</div>
    </div>

</body>
</html>

Explanation:

  • Visible: The content overflows and is visible outside the box.
  • Hidden: The content that overflows is clipped, and only the part that fits within the box is visible.
  • Scroll: Scrollbars appear, allowing the user to scroll to see the overflowing content.
  • Auto: Scrollbars appear only if the content overflows, similar to scroll but only when necessary.

Additional Properties:

overflow-x: Controls the horizontal overflow.

overflow-y: Controls the vertical overflow.

Syntax:


selector {
    overflow-x: visible | hidden | scroll | auto;
    overflow-y: visible | hidden | scroll | auto;
}

Example:


.box {
    width: 200px;
    height: 100px;
    border: 1px solid black;
}

.x-scroll {
    overflow-x: scroll;
    overflow-y: hidden;
}

In this example, the x-scroll class allows horizontal scrolling but hides any vertical overflow. This is useful when you want to control scrolling behavior separately for horizontal and vertical content.