DEV Community

ABISHEK M
ABISHEK M

Posted on

CSS Overflow

CSS overflow is used to control what happens when the content inside an HTML element is larger than the available space. This commonly happens when an element has a fixed width or height and the content does not fit inside it. Instead of allowing the content to create layout problems, we can use the overflow property to control it.

There are four commonly used values of the overflow property: visible, hidden, scroll, and auto.

1. overflow: visible

visible is the default value of the overflow property. The content that goes outside the element will still be visible.

.box {
  width: 200px;
  height: 50px;
  overflow: visible;
}
Enter fullscreen mode Exit fullscreen mode

If the content is larger than the box, it will continue outside the box.

2. overflow: hidden

hidden hides the content that goes outside the element.

.box {
  width: 200px;
  height: 50px;
  overflow: hidden;
}
Enter fullscreen mode Exit fullscreen mode

This is useful when we want to prevent extra content from appearing outside the container.

3. overflow: scroll

scroll adds scrollbars to the element. Users can scroll through the content that does not fit inside the box.

.box {
  width: 200px;
  height: 50px;
  overflow: scroll;
}
Enter fullscreen mode Exit fullscreen mode

The scrollbars are available even if the content does not always need scrolling.

4. overflow: auto

auto adds scrollbars only when the content is larger than the container.

.box {
  width: 200px;
  height: 50px;
  overflow: auto;
}
Enter fullscreen mode Exit fullscreen mode

This is commonly used because it provides scrolling only when necessary.

overflow-x and overflow-y

We can also control horizontal and vertical overflow separately using overflow-x and overflow-y.

.box {
  width: 200px;
  height: 100px;
  overflow-x: auto;
  overflow-y: hidden;
}
Enter fullscreen mode Exit fullscreen mode

Here, horizontal scrolling is allowed, while vertical overflow is hidden.

CSS overflow is an important property for controlling content that does not fit inside an element. visible shows the extra content, hidden hides it, scroll provides scrollbars, and auto provides scrollbars only when required. By understanding these values, we can create cleaner layouts and prevent unwanted content from affecting the design of a webpage.

Top comments (0)