Убираем горизонтальный скролл в мобильной версии сайта
Admin
05.05.2017 , обновлено: 13.09.2017
CSS, WordPress
Как убрать прокрутку по горизонтали в мобильной версии сайта. Как настроить css стили, чтобы скроллинг влево и вправо при просмотре через телефон не работал. Это же касается отключения горизонтальной прокрутки на iPhone.
Для выполнения этих задач нужно в стилях CSS своего сайта прописать следующее:
Чтобы убрать горизонтальный скролл одного HTML тега html или body не всегда достаточно, чтобы прокрутка исчезла. Обязательно нужно добавить overflow-x: hidden; к обоим тегам.
Если это не помогает, значит нужно искать ошибки в дизайне сайта. Какой-то элемент в дизайне сайта выходит за края и тем самым стиль overflow-x: hidden; перестаёт работать.
У меня так случилось с плагином Antispam Bee на сайте WordPress. Версия плагина 2.7.0 работала отлично, а как вышла версия 2.7.1, то плагин внёс в дизайн сайта какой-то лишний элемент.
Я долго искал причину ошибки, прежде чем понял, что причина вызвана плагином. Сначала пришлось потратить несколько часов и перелопатить весь css код на своём сайте. И только когда ничего не помогло, пришла догадка, что возможна причина в некорректном вмешательстве плагинов в работу сайта.
Как оказалось плагин Antispam Bee вносил что-то своё в дизайн формы комментариев. При этом видимого изменения не было.

А внутри HTML кода он вносил изменения и эту форму:
Менял на следующую:
В результате какой-то невидимый элемент выходил за границу экрана. Элемент не отображался и потому понять, что именно стало причиной неисправности было затруднительно. И настольная версия браузера и мобильная никаких лишних элементов не показывала.
Я так и не нашёл как победить эту ошибку, не изменяя свои стили. Пришлось внести коррективы у себя в CSS. Вместо указанного стиля у себя на сайте:
Я уменьшил поле комментариев со 100% до 97%.
После этого возможность горизонтального скролинга исчезла.
Читайте также
У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.
Комментарии к статье “ Убираем горизонтальный скролл в мобильной версии сайта ” (10)
Спасибо
помогло html не убирал, теперь все нормально
У меня сайт без плагина, делал адаптивную верстку давно. А сейчас стал замечать, есть горизонтальная прокрутка в одну сторону с права на лево. Не знаю что и делать, только догадываюсь, что где-то править надо. А где? Сайт mycompplus.ru

На разрешении в 768 у вас примешивается стиль pill_m, в котором задано width: 768px !important;. Этот участок нужно переписать.
![]()
Ребята, такая же проблема. Кто поможет исправить?

Sam, Как описал мне админ, мне это помогло
Юрий, спасибо за обратную связь. Можешь посмотреть у меня? Я плохо еще шарю. У меня проблема в кнопке scroll-on-top была. Я установил плагин до темы и он видимо взял произвольную ширину. Удалил кнопку, почистил кэш и все равно не помогает. Видимо этот плагин внес изменения в код, как пишет автор, но я не совсем понимаю как по аналогии решить проблему(что и куда прописать и исправить). Если не трудно, оставь контакт для связи. Вот больной engineeringdoc.ru
![]()
Посмотрел сайт, ответ дан в первом абзаце этой статьи. Только не говорите, что вы пробовали Вам надо поставить overflow-x: hidden;.
![]()
Спасибо за обратную связь. В какой файл это добавить, если я собрал на конструкторе и движок wp. Я так понимаю что это файл с css, но где он находится(в какой папке) и как называется не понимаю. Подскажите для «особо умных в этом деле»
P. S. Очень хочу исправить сам, но как слепой котенок уперся в угол.
![]()
Все сработало! Я вставил команду через внешний вид-> настроить->дополнительные стили, для тех у кого wordpress. Всем спасибо!
![]()
Добрый день! Подскажите, что нужно сделать у меня, чтобы убрать горизонтальный скролл. Сайт: sst-26.ru
How to Hide the Scrollbar in CSS

Designing a website exactly how you want often requires cutting out the excess — some whitespace here, an underline there, or, in today’s case, the scrollbar.

Whether for design or functionality reasons, it’s easy to hide the scrollbar on a page or page element with a bit of CSS. There are multiple ways to do this — hiding the scrollbar while allowing scrolling, hiding it while disabling scrolling, and keeping the scrollbar hidden only until it’s needed — some of which will work better based on your case.
To meet your design needs, this guide will cover all of these methods. Let’s get started.
Как убрать полосу прокрутки с помощью CSS
Если у вас возникла необходимость убрать полосу прокрутки на сайте, есть легкий способ это реализовать с помощью CSS свойства.
В этой статье я расскажу, как на сайте убрать горизонтальную и вертикальную полосу прокрутки.
Как убрать горизонтальную полосу прокрутки
Итак, допустим, вы имеете вот такой сайт, где есть горизонтальная полоса прокрутки и вертикальная

Но вам необходимо убрать только горизонтальную полосу прокрутки.

Для этого открывайте свой файл со CSS стилями и добавляйте свойство overflow-x к селектору «html» или к «body»

Как убрать вертикальную полосу прокрутки
Допустим, вам уже необходимо убрать только вертикальную полосу прокрутки.

Для этого открывайте свой файл с CSS стилями и добавляйте свойство overflow-y к селектору «html» или к «body»

Как убрать горизонтальную и вертикальную полосу прокрутки
Допустим, вам необходимо убрать вертикальную и горизонтальную полосу прокрутки.

Для этого открывайте свой файл с CSS стилями и добавьте свойство overflow к селектору «html» или к «body»
или же добавьте свойство overflow-x и overflow-y к селектору «html» или к «body» :

Как и обещал – ничего сложно здесь не было.
Внимание , прежде чем убирать полосу прокрутки, подумайте, действительно ли вам это нужно.
How to Disable Scrolling on a Webpage with HTML, CSS, and JavaScript?
Scrolling a webpage while navigating can be controlled by using some JavaScript and CSS or either one of them as well. We shall explore different methods to disable and enable the scrolling functionality of a webpage along with some example code snippets.
Pre-requisite
The prerequisite for understanding this article is the basic understanding of CSS and JavaScript DOM methods like querySelector , and getElementById as well as adding the event listeners to HTML elements.
By Overriding the window.onscroll Function
One of the ways to disable scroll on a webpage is using the window.onscroll event. Let's understand this event.
window.onscroll
The onscroll event on windows is triggered when the window's scrollbar is being scrolled.
We can set the position of this windows.onscroll event to a fixed value then it will prevent the page from scrolling in the vertical or horizontal direction or both.
To do this we need to fix the vertical and horizontal position of the page to the current values which can be done using the following JavaScript functions.
Calculating the current vertical position of the page: To calculate the current vertical scroll position of the web page in pixels document.documentElement.scrollTop and window.pageYOffset functions are used with OR (|) operator because one of them may return 0 value in some of the browsers.
document.documentElement.scrollTop method of JavaScript calculates the number of pixels from the top of the webpage by which the page is scrolled down.
The window.pageYOffset method of JavaScript also calculates the number of pixels from the top of the webpage by which the page is scrolled down. Since some of browsers do not support the former method then this method comes as an alternative.
Calculating the current horizontal position of the page:
To calculate the current horizontal position of the webpage in pixels document.documentElement.scrollLeft and window.pageXOffset values functions are used with the OR (|) operator because one of them may return 0 value in the browsers.
The document.documentElement.scrollLeft method is used to get the number of pixels to the left of the page by which the webpage is displaced to the right.
window.pageXOffset values method is also used to get the number of pixels to the left of the page by which the webpage is displaced to the right but the former method is not supported by some of the browsers, therefore, this method comes as an alternative.
Now, to assign the above-calculated values to the windows.scroll event we may use the window.scrollTo() function and pass the calculated values in this function as arguments to fix the horizontal and vertical position of the webpage.
Let's see the implementation of the above functionality.
Let's try to understand the above snippet. The output of the above code looks like this.
Output:
Here, when we click the Disable Scrolling button then we trigger the function disableScroll() where we are calculating the scroll position in the vertical direction in the scrollTop variable and the scroll position in the horizontal direction in the scrollLeft variable. After calculating these values we assign them to the scroll event of the window using the function called window.scrollTo(scrollTop,scrollLeft) .
When the Enable Scrolling button is clicked then we trigger the function enableScroll() which simply puts the value of the window.scroll event to blank and enables scrolling.
By Setting the Height of the Body to 100% and Overflow to Hidden
Scrolling of the webpage can also be disabled by using only the CSS using the overflow property. In this method, we set the height of the element for which the scroll is disabled to 100% such that it covers all the space of its parent container, and then we set the overflow property to hidden.
For the horizontal scrolling, we use the property overflow-x and set it to hidden.
We shall use JavaScript to add these properties to the HTML document.
Let's see the implementation
Output:
It will have the same effect as with the window.onscroll but with a few differences. Let's discuss those differences.
- It will disable the keyboard scrolling as well. Therefore we won't be able to move up and down using a keyboard, mouse or spacebar, etc.
- It will disable the touch scroll as well
- It will disable the scroll up and down by selecting the text.
Set overflow-x to Hidden to Disable Horizontal Scroll Bar in CSS
For disabling the horizontal scrolling we can set the property overflow-x to hidden along with the height is set to 100%. Everything else remains the same. Let's see the implementation for this.
Output:
Preventing Keyboard Scroll Using JavaScript
Suppose, we want to prevent only the keyboard scroll but want to keep other scrolls, in that case, we need to add a keydown event Listener because this will detect which key is pressed and we can prevent the default behavior of the document if the key pressed is keyboard arrows, spacebar, shift+space bar, pageup, pagedown, etc.
We create an event Listener which takes an event argument and checks if the event(button pressed) has a keyCode equal to some of the keycodes already stored in an array. If it matches with one of them then we call the function preventDefault() and return false. This will disable the scrolling effect using that key.
To enable the scrolling effect we simply remove that eventListner added with that particular keypress.
Let's see the implementation of the above strategy.
Output:
Preventing Touch Scroll Using JavaScript
To prevent the touch scroll, we need to add a touchmove event listener which prevents the default behavior while we perform touch scroll. This can be accomplished by creating a function called disableTouchScroll() which takes a touchmove event and prevents the default behavior using the function preventDefault() and stops the propagation using the stopPropagation() function of the event.
This can be implemented as follows
Applying CSS to Hide the Scrollbar in Website's Code
To hide the scrollbar in the website's code we can use the -ms-overflow-style property in the body element where we can set it to node as well as the -webkit-scrollbar property where we set the display property for this as none, this ultimately hides the scrollbar.