ScanSkill
CSS Examples

How to Display the Scrollbar Only When Content Overflow

In this example, we will see how to display the scrollbar only when content overflow. When we define the overflow property to scroll as overflow: scroll, the scrollbar displays even when the content does not overflow. So to display the scrollbar only when the content overflow, we can use the overflow: auto.

Prerequisites

Example

HTML

        <div class="content">
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laborum magni quibusdam inventore sapiente
            consequatur reprehenderit hic, modi nesciunt? 
        </div>
        <div class="content">
            Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laborum magni quibusdam inventore sapiente
            consequatur reprehenderit hic, modi nesciunt? Alias ducimus asperiores reprehenderit dignissimos qui eius
            placeat exercitationem magnam voluptas labore? Lorem ipsum dolor sit amet consectetur adipisicing elit.
            Temporibus vitae harum fuga. Aliquid expedita laboriosam labore, quasi aperiam eligendi ipsum, facere iure
            quae asperiores provident at magni corrupti consequuntur nam.
        </div>

CSS

        .content {
            overflow: auto;
            width: 200px;
            height: 200px;
            border: 1px solid black;
        }

Output

How to Display the Scrollbar Only When Content Overflow

Here, the scrollbar is displayed only when the content overflow. When the content does not overflow, the content box is displayed without the scrollbar.

Conclusion

In this example, we saw how to display the scrollbar only when content overflow. We used the overflow: auto to display the scrollbar when the content overflow and to hide the scrollbar when content doesn't overflow.