DEV Community

Mạnh Đạt
Mạnh Đạt

Posted on

Understanding overflow in CSS

If you have written CSS for a while, you'd probably encountered overflow property. It governs the display of overflow content in a container.

Let's have an example. I have a div that is 300px width and 100px height like this:

#container {
 border: 2px solid blue;
 height: 100px;
 width: 300px;  
}

Alt Text

Let's put some text inside:
Alt Text

Everything is fine. Let's put some more text:
Alt Text

As you can see, when there is more content than the capacity of the container, the text is overflowed.

But is this the only behavior? Obviously not.

Overflow possible values

There are four possible values of overflow:

  1. visible (default value)
  2. hidden (overflowed content will be clipped)
  3. scroll (scroll bars will be added to the container No matter the content's length)
  4. auto (scroll bars will be added when necessary)

Overflow values in action

Let's have a look at overflow values in action

visible

This is the default value. So, I'll reuse the above screenshot:
Alt Text

hidden

Alt Text

scroll

When overflow occurs:
Alt Text

When there is no overflow:

Alt Text
=> there are scroll bars no matter what :O

auto

When there is no overflow:
Alt Text

When overflow occurs:
Alt Text

overflow-x and overflow-y

You are not limited to using overflow only. You can use overflow-x and overflow-y to set the behavior on these axis separately (using the same value as above).

Discussion (2)

Collapse
jharteaga profile image
Jose Arteaga

Thanks for sharing with nice examples! I just have a doubt, let me put you an example:

I have two divs: First div is my NavBar and the Second div will be my content. My NavBar will have a fixed position, but I don't want that my content div scrolls behind the NavBar. Can I use "Scroll Overflow" in my content div, in order to allow scrolling only inside the content div without going behind the NavBar div?

Collapse
datmt profile image
Mạnh Đạt Author • Edited on

Hi Jose,

That is possible. However, you need to set a fixed height for your content div.
Take a look at my example below. Is this what you want to achieve?

nav bar