Div с горизонтальной прокруткой css

Pure CSS Horizontal Scrolling

The web is a rather vertical place. You read a web site like you read a physical page: left to right, top to bottom. But sometimes, you want to step away from the verticality of it all and do something crazy: make a horizontal list. Or even crazier, a horizontal site! I’d be nice if we could do something like this:

Unfortunately, that’s not going to happen. It’s not even on the roadmap for CSS. That’s too bad, as at the company I work for this would be quite useful. We do quite a few web presentations. Presentations are a very horizontal thing – usually slides have a 4:3 or 16:9 radius. This means we always have a struggle between the horizontality of presentations and the verticality of web technologies. And by we, I mean me. But if there’s one thing I like, it’s a challenge.

The specific use case that led to me digging into this idea that a customer wanted to show all their products on a single slide. Of course, their product catalog was way too big to put in a single view. So we decided to split them up into three categories, each horizontally scrollable. So the three most prominent product in each category were visible and less important products were still easily accessible.

  • Create a container with items
  • Rotate the container 90 degrees counterclockwise so the bottom is to the right
  • Rotate the items back to correct-side up
Читайте также:  Цикл while питон пример

Step 1) Set up the container

Make a , and make a bunch of child elements.

In this example, our side-scrolling container will be 300px wide, with 8 items of 100×100px each. These are arbitrary sizes; they could be anything.

 
item 1
item 2
item 3
item 4
item 5
item 6
item 7
item 8

The height of the container will become the “width” and vice-versa. So below, the “width” of our container will be 300px:

.horizontal-scroll-wrapper > div

Step 2) Rotating the container

Now we rotate the container -90 degrees with a CSS transform . And there you have it: a horizontal scroller.

There’s just one tiny issue: our children have rotated too, and now anything within is on its side.

Step 3) Rotate the children back upright

How would we go about getting the children upright again? Rotate them back using another, opposite CSS transform .

.horizontal-scroll-wrapper > div

Step 4) Fixing the positioning

It’s starting to look alright, but there are still some issues.

By rotating the wrapper using the top right as an anchor point, our left side has shifted by the width of the container. If you find this difficult to understand, just put your finger on the top right corner of a page and rotate it. The solution: shift it back with translateY .

Better. But the first item is still missing, due to the same phenomenon happening to the items. We could fix this by giving the first child a top margin of its width or by translating all items the same way we did the wrapper. The easiest way I’ve found though is to add a top padding to the wrapper equal to the item width, creating a kind of buffer for the items.

Here’s another where you can see non-square children:

I have tested on the devices immediately available to me.

Device OS Browser works?
Desktop Win10 Chrome 54 Y
Desktop Win10 Firefox 47 Y (w scrollbars)
Desktop Win10 IE11 Y (w scrollbars)
Desktop Win10 Opera 41 Y
Desktop Win10 Vivaldi 1.4 Y
Laptop (touch screen) Win10 Chrome 54 N
Samsung Galaxy S3 Android 4.3 Chrome Mobile 52 Y
Samsung Galaxy S6 Android 5.0 Chrome Mobile 52 Y
Nexus 6P Android 6 Chrome Mobile 52 Y
iPad2 iOS Chrome Mobile 52 N
iPad2 iOS Safari Mobile 9.0 N
iPad Air 2 iOS Safari Mobile 9.0 N

Since the styling of scrollbars is currently only supported by WebKit/Blink, Firefox and IE still show the ugly gray ones. You could sniff this out with JavaScript and hide them completely, but that’s stuff for another tutorial.

Using the mouse scroll wheel works great on desktops. My laptop was a different matter, though. Both the touchscreen and the touchpad acted as though the div was not rotated.

I was kind of surprised to find that Android actually understood that the container had been rotated, and let you scroll sideways by swiping left and right.

iOS on the other hand did not play nice. It acted like the container did not get rotated, so you have to swipe up and down to scroll sideways, which of course is counterintuitive. Also, swiping left and right moves the items up and down in their wrapper, which is unexpected and weird. Setting the overflow to hidden does not alleviate this issue.

According to Can I Use, CSS transforms are currently supported by over 93% of users (at the time of this writing, November 2016), so there’s no issue there.

Beware of using this in production, though. I have tested this on some devices, but not at all extensively or in depth.

The greatest issue is with touch inputs that requiring you to swipe up and down to go left and right. A possible solution would be to include a message on your site explaining this, but you’d have to rely on people actually reading your message. And even then it’d still be counterintuitive. Another possible solution would be to capture the touch input with JavaScript on those devices, but then you’d be better off just doing the whole thing in JavaScript and foregoing this CSS hack completely.

Источник

Как создать горизонтально прокручиваемые контейнеры

Контейнеры с горизонтальной прокруткой становятся все более популярными. Особенно среди мобильно оптимизированных сайтов, где они используются для уменьшения высоты веб-страниц.

После реализации нескольких таких элементов я захотел выяснить, как с помощью минимального объема кода создать горизонтальную прокрутку, которая корректно работает, на всех типах пользовательских устройств.
Сначала создадим контейнер и дочерние div внутри него, которые будут прокручиваться по горизонтали.

 

Card

Card

Card

Card

Card

Card

Card

Card

Card

Существует два способа сделать эти div горизонтально прокручиваемыми.

Метод пустого пространства

Вот CSS, который нам нужен. Никаких префиксов и jQuery. Простое использование overflow и еще одного свойства.

Для контейнера нужно отключить вертикальную прокрутку ( overflow-y ) и включить горизонтальную ( overflow-x ). Затем для каждой карточки установим display : inline-block , чтобы они отображались в строке.
Свойство CSS, с которым вы, вероятно, не встречались — это white-space : nowrap . Оно используется для управления тем, как текст переносится в контейнере. В данном случае мы хотим отключить перенос с помощью значения nowrap .
Четыре строки свойств CSS, и у нас есть горизонтально прокручиваемый контейнер.
Как насчет поддержки браузерами? Идеально. Если вы не заботитесь об Internet Explorer или Edge. В Microsoft говорят, что они включат поддержку этого свойства в будущую версию браузера Edge.

Метод Flexbox

Flexbox также может выполнить эту работу.

Мы используем flex-wrap для достижения того же эффекта, что и в предыдущем примере.
Поддержка браузерами решения на основе flexbox лучше. Оно работает в IE и Edge.

Overflow прокрутка

В iOS веб-страницы прокручиваются с импульсом ускорения. Если вы быстро протянете пальцем вверх или вниз, страница будет продолжать прокручиваться после того, как уберете палец. Если вы достигнете верхней или нижней части страницы, он а отскочит назад от конца контейнера, прежде чем встанет на место.
К счастью, эту проблему легко решить:

Теперь у нас есть прокрутка для горизонтального контейнера. Вот пример того, как это выглядит:

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

По умолчанию контейнер с прокручиваемым контентом будет иметь полосы прокрутки. Но что, если мы не хотим добавлять скроллинг? Такое решение легко реализовать. Хотя работает оно только в браузерах на WebKit.

Заключение

Контейнеры с горизонтальной прокруткой становится все более распространенными.Поэтому лучше сохранить эти примеры:они понадобятся вам в будущем. Также можно обернуть код в медиа-запрос и отобразить горизонтальную прокрутку только для определенных устройств. И никакой головной боли с jQuery!

Источник

Horizontal scrolling div with arrows using HTML and CSS

Horizontal scrolling div with arrows using HTML and CSS

In this tutorial, we will learn how to create a horizontal scrolling div with arrows using HTML and CSS.

We can make a div horizontally scrollable using the overflow property in CSS.

To make div horizontally scrollable we have to use the x and y-axis properties. We have to set the overflow-y : hidden and make overflow-x:auto , this will hide the vertical scrollbar to hidden and make the div scroll horizontally.

So here, we will make a horizontal scrollable div one without arrows and another with arrows for navigation.

Horizontal Scrolling div using HTML and CSS

Here, we will code the div to make them scrollable horizontally.

Let’s first code our HTML page.

div class="cover"> div class="scroll-images"> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div class="child"> img class="child-img" src="img.jpeg" alt="image" /> div> div> div> 

Here, we have a parent div with class=»scroll-images» and inside it, we have child elements with class=»child» . And each child event has an image inside it.

Next, we will make the parent element (scroll-images) horizontally scrollable using CSS.

Let’s code the CSS now

.scroll-images < width: 100%; height: auto; display: flex; flex-wrap: nowrap; overflow-x: auto; overflow-y: hidden; scroll-behavior: smooth; -webkit-overflow-scrolling: touch; > .scroll-images::-webkit-scrollbar < width: 5px; height: 8px; background-color: #aaa; > .scroll-images::-webkit-scrollbar-thumb < background-color: black; > .child < width: 120px; height: 100px; margin: 1px 10px; overflow: hidden; > 

Here, we have used display:flex in the parent div and made overflow-y:hidden and overflow-x: auto . This will make the div scroll horizontally.

We have set the flex-wrap:nowrap , so that it doesn’t wrap and is forced onto one line to maintain the horizontal scroll in mobile devices too.

The -webkit-overflow-scrolling: touch is used so that any mobile or touch-screen devices can use the momentum-based scrolling for the given element.

The ::-webkit-scrollbar is used to give color to the scrollbar.

And ::-webkit-scrollbar-thumb is used to give color to the scroll-thumb of the div.

Now let’s add the arrows on both sides of the horizontal parent div and code the functionality with some JavaScript.

Horizontal Scrolling element with arrows

To add the arrows on both sides we have to add some codes to our HTML.

First, we will add the arrow button on both sides of the element.

So we have to wrap the div (scroll-images) with another div with class=»cover» . Added both the left and right buttons on it.

div class="cover"> button class="left" onclick="leftScroll()">Left button> div class="scroll-images"> div> button class="right" onclick="rightScroll()">Left button> div> 

The cover will be position:relative and the buttons will be position:aboslute to position them on both sides.

We have also added two functions with the click event on the button: leftScroll() and rightScroll().

.cover < padding: 0px 30px; position: relative; > .left < position: absolute; left: 0; top: 50%; transform: translateY(-50%); > .right < position: absolute; right: 0; top: 50%; transform: translateY(-50%); > 

Now, we have to code the function to navigate through the child elements in the horizontal div.

  

The scrollBy() method scrolls an element by a given amount.

When the left arrow is clicked the leftScroll() function is triggered and the element will move 200 on the x-axis and when the right arrow is clicked the element move -200 on the x-axis of the horizontal div.

Note:

If you don’t want to display the scrollbar below add this to your CSS code.

.scroll-images::-webkit-scrollbar

Complete Code:

Other Articles You’ll Also Like:

Источник

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