Cascading Style Sheet (CSS)

CSS Overflow - Taking care of extra content

There are times, when the content inside an element is more, which leads to content overflowing outside the element. CSS overflow property allows us to handle the overflowing content either by hiding it or by adding a scroll bar to the element.

The overflow property can have the following values:

  1. visible → This is the default value. In this case, no action is taken on the overflowing content and it is visible outside the element as well.
  2. hidden → In this case, the overflowing content, which is outside the element becomes invisible i.e. it is hidden.
  3. scroll → In this case, a scroll bar is added to the element, hence allowing it to hold all the content in it.
  4. auto → If the content is less, this acts like visible but as the content starts to overflow outside, this property starts acting like scroll and adds a scroll bar to the element.

By default all the HTML tags are auto adjusting i.e. they can grow to infinite height and can hold all the content. But the need of overflow property arises, in case of fixed height elements.

CSS Overflow Example


Overflow Visible overflow:visible

This is the default value, and allows the content to overflow out of an element of fixed height.

div {
    width: 300px;
    height: 50px;
    background-color: #cccccc;
    /* setting overflow visible */
    overflow: visible;
}

Live Example →


Overflow Hidden overflow:hidden

This value of the overflow property, hides the extra content which is flowing outside the element by making it invisible.

div {
    width: 300px;
    height: 50px;
    background-color: #cccccc;
    /* setting overflow hidden */
    overflow: hidden;
}

Live Example →


Overflow Scroll overflow:scroll

This value of the overflow property, introduces a scroll bar to the element, as content starts to overflow. Hence no content is hidden, you can easily scroll using the scroll bar and see the complete content.

div {
    width: 300px;
    height: 50px;
    background-color: #cccccc;
    /* setting overflow scroll */
    overflow: scroll;
}

Live Example →


Overflow Auto overflow:auto

This value of the overflow property, acts as default till the content is less, as content starts to overflow, this acts like scroll.

div {
    width: 300px;
    height: 50px;
    background-color: #cccccc;
    /* setting overflow auto */
    overflow: auto;
}

Live Example →


More about Overflow...

We can even control the overflow property differently for horizontal and vertical overflow using overflow-x and overflow-y property. As you must have noticed in the last Live Example, on adding overflow:scroll both horizontal and vertical scroll bars are introduced.

div {
    overflow-x: hidden; /* Hide horizontal scrollbar */
    overflow-y: scroll; /* Add vertical scrollbar */
}

Live Example →