JavaScript Answers

How to check with JavaScript if div has overflowing elements?

Spread the love

To check if a <div> element has overflowing content using JavaScript, you can compare its clientWidth and scrollWidth properties.

If scrollWidth is greater than clientWidth, it means that the content inside the <div> is overflowing horizontally.

Similarly, you can check for vertical overflow by comparing clientHeight and scrollHeight properties.

Here’s how you can check for horizontal overflow:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check for Overflowing Content</title>
        #overflowDiv {
            width: 200px; /* Adjust the width of the div */
            height: 100px; /* Adjust the height of the div */
            overflow: auto; /* Enable scrolling */
            border: 1px solid black;
    <div id="overflowDiv">
        <!-- Content that may overflow -->
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nec mauris eu urna commodo pulvinar.

        // Check for horizontal overflow
        var overflowDiv = document.getElementById('overflowDiv');
        var hasHorizontalOverflow = overflowDiv.scrollWidth > overflowDiv.clientWidth;

        if (hasHorizontalOverflow) {
            console.log('The div has horizontal overflow.');
        } else {
            console.log('The div does not have horizontal overflow.');

In this example, we have a <div> element with the ID overflowDiv containing some content.

We apply CSS styles to the div to limit its width and height and enable scrolling if its content overflows.

Then we use JavaScript to check if the scrollWidth of the div is greater than its clientWidth. If it is, then there is horizontal overflow.

Depending on whether there’s horizontal overflow or not, we log the appropriate message to the console.

You can adapt this approach for vertical overflow by comparing scrollHeight and clientHeight.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *