How to prevent body scrolling but allow overlay scrolling in CSS ?
In this article, we are going to learn how we can prevent body scrolling but allow overlay scrolling. The objective is to add a feature to an overlay where we will be able to scroll the overlay but we will not be able to scroll the background content. It means when the overlay is opened, the background/body is fixed and it doesn’t move. Generally, we can use this process to create a modal type effect in our design. In CSS there is no default property that we can add to make this process work.
Approach: To prevent body scrolling but allow overlay scrolling we have to switch the overflow to be hidden when the overlay is being shown. And while the whole page’s overflow is hidden or the scroll is disabled the overflow in the y-axis of the overlay is enabled and the overflow can be scrolled.
- overflow: It allows us to manage what occurs when the content of an element is too large to fit inside a given space. This causes the material to “overflow” into another location, either horizontally (X-axis) or vertically (Y-axis) (Y-axis). It can be specified in the two-axis separately with overflow-x and overflow-y. It can take the following values.
- visible: If no value is supplied for the overflow property, this is the default value. We can view our stuff clearly when it overflows into another region because of this characteristic.
- hidden: The part of the text that overflowed will be taken out – it will be “invisible” if we use the hidden value. We don’t have to be concerned about the space taken up by the overflow. The material will no longer be in the region where it overflowed once it has been clipped out.
- scroll: The scroll value also trims the text and adds a scrollbar, so we can scroll and see what was chopped off.
- auto: The auto value detects overflow and inserts a scrollbar in the appropriate direction.
Example: The above approach is demonstrated in the below-given code.