I’m working on a web project where I need to customize the appearance and behavior of a container element. Specifically, I want to remove the scroll bars from the container and prevent users from selecting text within it. I’ve tried various CSS properties and techniques, but I haven’t found a solution that works reliably across different browsers.
Here’s what I’ve attempted so far:
<div class="custom-container">
<!-- Content goes here -->
</div>
CSS:
.custom-container {
width: 300px;
height: 200px;
overflow: hidden; /* Hides scroll bars, but still allows scrolling */
user-select: none; /* Prevents text selection, but doesn't work consistently */
}
While setting overflow: hidden successfully hides the scroll bars, it still allows users to scroll the content using mouse or touch gestures. Additionally, the user-select: none property prevents text selection, but it’s not supported uniformly across all browsers.
Could someone suggest a reliable CSS-based solution to achieve both hiding scroll bars and preventing text selection within the container element? Any insights or alternative approaches would be greatly appreciated!
>Solution :
you can use a combination of CSS properties and some additional techniques. Here’s how you can modify your CSS:
.custom-container {
width: 300px;
height: 200px;
overflow: hidden; /* Hides scroll bars */
}
.custom-container::-webkit-scrollbar {
display: none; /* Hide scrollbars on WebKit browsers (Chrome, Safari, etc.) */
}
.custom-container {
-ms-overflow-style: none; /* Hide scrollbars on Internet Explorer */
scrollbar-width: none; /* Hide scrollbars on Firefox */
}
.custom-container {
user-select: none; /* Prevent text selection */
-moz-user-select: none; /* For Firefox */
-webkit-user-select: none; /* For WebKit browsers */
-ms-user-select: none; /* For Internet Explorer */
}
Explanation:
overflow: hidden;: This property hides the scroll bars but still
allows users to scroll the content using mouse or touch gestures.::-webkit-scrollbar: This pseudo-element is used to style the
scrollbar on WebKit browsers. Settingdisplay: none;hides the
scrollbar.-ms-overflow-style: none;: This property is specific to Internet
Explorer and Edge, and it hides the scroll bars.scrollbar-width: none;: This property, along with the
-moz-scrollbarselector, hides the scroll bars on Firefox.user-select: none;: This property prevents text selection within
the container. Additional vendor-specific prefixes are used for
cross-browser compatibility.