A Guide to Using the CSS Overflow Property
Discussing visible, hidden, scroll, auto, overflow-x, and overflow-y
Sometimes, the content or a part of a webpage doesn’t fit and exceeds the borders of its container. In that case, CSS provides us with a solution with its
overflow property so we can handle the overflow problem.
In this piece, I will show you how to use the
overflow property with its different kinds of values.
The Overflow Property
overflow property in CSS is used to clip, hide, or scroll an element's content when the content is bigger than its own specified area.
There are four different values of CSS overflow we can use:
overflow: visible | hidden | scroll | auto
We can set these values to horizontal, vertical, or both:
overflow-x: only horizontal.
overflow-y: only vertical.
overflow property only works when an element is a block-level element and has a defined height.
Let’s explain the details with an example.
Consider that we have a
<div> box with some text inside.
Normally, the text will fit inside the box because the height adjusts itself automatically based on the size of its content (length of the text):
So, no matter how long the text is, it will always fit its container (box).
However, sometimes elements may have a fixed-sized width or height. In this case, when the text is long enough, it will overflow:
In this example, the blue box has a fixed
80px, but the text is larger. Now, here, we can use the
overflow property to fix this issue by hiding or adding a scroll bar, based on which value we use.
visible is the default value. If the content overflows, we will still be able to see it:
When we set the
hidden, it will clip the content and hide the rest:
scroll value will again clip the content but it will add a scroll bar so we can see the rest of the content by scrolling:
auto value will also add a scroll bar but the user will see the scroll bar only when the content overflows.
overflow: scrolladds a scroll bar, regardless of whether we need it.
overflow: autoadds the scroll bar only when it is necessary.
overflow-x and overflow-y
So, above I explained what
overflow does and the values of it.
We can also use the same values for
overflow-y. But what's the difference?
For example, let’s take the
scroll value. When both the
width and the
height of the element are too small,
overflow: scroll will add scroll bars both vertically & horizontally:
When we use
overflow-x instead of
overflow, the scroll bar will be added to the element only horizontally:
overflow-y adds the scroll bar only vertically:
We can even assign different values to
overflow-y at the same time.
So, this is basically what
overflow does. If you have any questions, don't hesitate to ask.
Thanks and see you soon!