How To Lock Scroll CSS

In web design, there are times when you might want to disable scrolling on a webpage or a specific element. This can be useful for creating a fixed header or footer, modal dialogs, or various other web design elements. In this tutorial, we will cover how to lock scroll using CSS.

Step 1: Identify the Element You Want to Lock

First, you need to identify the element on your web page that you want to lock the scroll on. For example, if you have a div element with the class .modal-dialog, you want to prevent scrolling when this modal dialog is displayed.

Step 2: Apply the CSS Rule

To lock the scroll, you need to apply a CSS rule with the overflow property set to hidden. This will prevent the content from overflowing and creating scrollbars. Add the following CSS rule to your stylesheet:

Step 3: Apply the Class to Your Element

Now that you have created the CSS rule, you can apply the .locked-scroll class to the element you identified in Step 1. To do this, simply add the class to the element’s HTML markup like in the example below:

Alternatively, you can add the class dynamically using JavaScript. For example, you can use the following JavaScript code:

Now, when the .modal-dialog element is displayed, the scroll will be locked.

Step 4: Lock the Body’s Scroll When Needed

If you want to lock the entire web page scroll when the modal dialog is displayed, you can apply the .locked-scroll class to the body element instead. This can be done using the following JavaScript code:

Remember to remove the class when you want to re-enable scrolling:

Full Code Example

Conclusion

Locking scroll using CSS is an essential technique for controlling the user experience on your website. By following this simple tutorial, you can disable scrolling on specific elements or the entire web page when needed. Don’t forget to unlock the scroll when it’s no longer required to ensure a smooth and enjoyable browsing experience for your users.