Полосы прокрутки

Как убрать полосы прокрутки?

Убрать горизонтальные или вертикальные полосы прокрутки со страницы, не зависимо от объёма страницы.

Решение

Перед тем как убрать полосы прокрутки с веб-страницы, подумайте, действительно ли вам это так необходимо. Отсутствие возможности прокрутки содержимого документа создает трудности посетителям сайта для просмотра информации. Если же существует острая необходимость построения дизайнерских изысков или желание создать своим читателям трудности, то вперед. Но вас предупреждали!

Способ основан на использовании свойства overflow , которое добавляется к селектору HTML, как показано в примере 1.

Пример 1. Страница без полос прокрутки

HTML5 CSS2.1 IE Cr Op Sa Fx

     html < overflow: hidden; >div 
Бла-бла

В данном примере используется значение hidden , которое «обрезает» весь контент выходящий за рамки элемента.

Также можно использовать свойство overflow-x , чтобы скрыть только горизонтальную полосу прокрутки и overflow-y — для сокрытия вертикальной полосы. В примере 2 показано добавление слоя с минимальной шириной 800 пикселов. При уменьшении окна браузера до этой величины, слой перестаёт менять свои размеры и появляется горизонтальная полоса прокрутки. С помощью свойства overflow-x полосы прокрутки скрываются.

Читайте также:  Php создание своих функций

Пример 2. Нет горизонтальной полосы прокрутки

HTML5 CSS3 IE Cr Op Sa Fx

       
Бла-бла

Свойства overflow-x и overflow-y входят в спецификацию CSS3 и не проходят валидацию при проверке стилей на CSS2.1.

Источник

Using CSS to hide scrollbars without impacting scrolling

Using CSS To Hide Scrollbars Without Impacting Scrolling

The scrollbar can make an otherwise elegant website look like it’s from the 90s, but thanks to new CSS properties, we can hide the scrollbar without impacting our users’ ability to scroll.

The scrollbar in the browser allows the user to scroll up and down on the page without having to take their hands off the keyboard or trackpad, but to make the page sleeker, some websites choose to hide the scrollbar altogether.

This guide will show you how to hide the scrollbar in several popular browsers by making use of modern CSS techniques. Without wasting any more time, let’s get right down to it.

N.B., to get the most out of this article, you should have a basic understanding of HTML and CSS

Reasons to hide the scrollbar

While it’s common practice not to mess with default browser styling due to accessibility concerns, when it comes to scrollbars, there are solid reasons you should hide them.

A scrollbar provides a visual cue for using your mouse or keyboard to scroll up and down. However, this visual cue isn’t needed for many layouts and design patterns, including ones that are static, such as a slideshow or product gallery. Hiding the scrollbar will create a smoother scrolling experience and remove some distractions from your site’s overall layout.

Hiding a scrollbar also helps you save space for other content on your page — it can make for a more consistent user experience across different devices because different operating systems may not render the scrollbar in the same way.
However, the most common reason to hide a scrollbar is to improve mobile viewing experiences.

When viewing an app, like Facebook, on their phone, most users expect scrolling to be vertical, with no need for horizontal movement since screens are usually tall and narrow. Hiding the scrollbar creates a more natural feel while reducing attention to the technical aspects of browsing.

These days, scrollbars are unnecessary for most websites; hiding them will give your site a clean look and feel that’s far more sophisticated than dated bars. Removing them from your site can also help with page load speed and browser window real estate.

Now you may be wondering how exactly you get rid of those pesky bars when they don’t seem to want to go away by themselves. We’ll go into detail about that below.

Over 200k developers use LogRocket to create better digital experiences

Learn more →

Hiding the scrollbar

Because of the fundamental differences between browsers, there’s no universal way of hiding scrollbars with CSS. Each browser has its own method, and we will look at all of them below.

In Chrome, Safari, Opera, and other WebKit-based browsers

To hide the scrollbar in WebKit-based browsers, you have to use the ::-webkit-scrollbar pseudo selector. ::-webkit-scrollbar is a pseudo-element in CSS used by developers to modify the look of a browser’s scrollbar.

With the ::-webkit-scrollbar pseudo selector, there’s a wide range of things you can do to a scrollbar. You can modify the arrows pointing up and down, change the track’s color, change the background, and more. But we’re only going to look at how to hide the scrollbar without impacting scrolling.

First, I’m going to add the HTML of a random website I’m building:

[email protected]&family=Staatliches&family=Titan+One&display=swap" rel="stylesheet">

The Best Crypto Marketing Agency

We'll help you promote your crypto and NFT projects through PRs, advertorials,
and Telegram groups on the most popular crypto news and influencer channels!

Contact us now

Our Services

NFT PROMOTIONS AND SHILLING

Promote your NFT with our celebrity endorsement and shilling services.

MODERATION AND AMAs

Get quality moderators for your community, and get access to premium AMA channels

INFLUENCER MARKETING AND PRESS RELEASES

Get celebrity influencer endorsement, and Get your PR instantly published on 100s of the biggest crypto and finance new sites!

There’s quite a bit of content there to make it scrollable. Here’s what the above code looks like:

Visible Scrollbar

As you can see, in the CodePen below, the scrollbar is visible on the right. To make it invisible without impacting scrolling, you just have to target the body element using the ::-webkit-scrollbar pseudo selector and set the display to none :

Now, the scrollbar is no longer visible, but the page is still scrollable for both the mouse and keyboard.

This same technique can be used to target elements with scrollable content and make the scrollbar invisible. For instance, if you need to make the scrollbar of a particular section invisible, you just need to target the section with the same code:

Note that this code only applies to WebKit-based browsers.

There are other methods to make the scrollbar disappear. For example, you could just target the scrollbar directly and reduce its width to zero:

You’ll get the same result without it impacting accessibility and keyboard scrolling.

In IE (Internet Explorer) and Edge

The syntax for hiding a scrollbar in IE and Edge is a bit different from WebKit-based browsers like Opera, Chrome, and Safari. Here, we have to use the -ms-overflow-style property.

According to CodeProject, “ -ms-overflow-style is a proprietary CSS property, specific to Internet Explorer and Microsoft Edge, which controls the behavior of scrollbars when an element’s content overflows.”

Unlike ::-webkit-scrollbar , you can’t use the -ms-overflow-style to customize the scrollbar. To use it to hide a scrollbar, you just have to use the code below.

If you’re targeting a particular element or section, use the following code:

If you’re targeting the entire page, use this code:

In Firefox

To successfully hide the scrollbar in Firefox, you just need to use the scrollbar-width:none property to target a section like this:

To target the scrollbar of the entire page in Firefox, you have to be a bit more careful. In the two sections above, we applied the scrollbar code to the body tag, and it worked, but with Firefox, we have to target the html tag instead:

Alternatively, you can choose to use this other method to hide the scrollbar in Firefox.

More great articles from LogRocket:

  • Don’t miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket’s Galileo cuts through the noise to proactively resolve issues in your app
  • Use React’s useEffect to optimize your application’s performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

Hiding the scrollbar conditionally

If there’s a particular section of your website that has scrollable content, keeping the scrollbar visible is beneficial for both usability and accessibility. But, as we said earlier, having a scrollbar that is always visible can ruin the aesthetics of your site.

Fortunately, there’s a workaround — we can make the scrollbar only visible on hover. This means if the target section is not active, the scrollbar will not come into play. Let’s create a test as an example:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"

With the above code, the scrollbar is hidden for that particular and only shows up when we hover over it:

Accessibility concerns

Hiding scrollbars on a website can create accessibility problems for users who rely on assistive technologies. Some examples are people who rely on screen readers, lack fine motor control, or have cognitive disabilities. Without visible scrollbars, these users may not be able to tell that a page is scrollable or know how far they have scrolled.

If you’re implementing hidden scrollbars, you should consider the potential accessibility issues that come with hiding scrollbars and take steps to ensure that all users can access and use the website’s content and functionality. This could include providing alternative methods for scrolling, such as keyboard commands, or offering a toggle to turn the scrollbar on and off.

Conclusion

If you are reading this, then by now, you fully understand the art of hiding scrollbars with CSS without impacting scrolling and accessibility. It’s important to note that when targeting sections that have scrollable content, leaving the scrollbar visible as a visual cue will help your users notice the section and not skip it by accident.

I hope this article has been of great help to you. See you in the next one.

Is your frontend hogging your users’ CPU?

LogRocket Dashboard Free Trial Banner

As web frontends get increasingly complex, resource-greedy features demand more and more from the browser. If you’re interested in monitoring and tracking client-side CPU usage, memory usage, and more for all of your users in production, try LogRocket.https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app, mobile app, or website. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — Start monitoring for free.

Источник

Оцените статью