Text slider html css

Create a slider with pure CSS

Actually, there is a clever way to do this with pure CSS, and not a single line of JS. And yes, that includes navigation buttons and breadcrumbs!

Take a quick look at the result we will get:

Step 1 — create your slider layout

First you need to create a space for your slider to go into, and of course, some slides!

div class="slider-container"> 
div class="slider">
div class="slides">
div id="slides__1" class="slide">
span class="slide__text">1span>
div>
div id="slides__2" class="slide">
span class="slide__text">2span>
div>
div id="slides__3" class="slide">
span class="slide__text">3span>
div>
div id="slides__4" class="slide">
span class="slide__text">4span>
div>
div>
div>
div>
  • slider-container is just the element on your site that you want the slider to go in.
  • slider is like the ‘screen’, or the viewport that will display all your slides.
  • slides will hold your slides. This is the element that actually scrolls to give the slider effect.
  • slide is each individual slide. Note that you need the slide class, and a unique id for each one.

.slider-container
background: linear-gradient(149deg, rgb(247, 0, 255) 0%, rgb(255, 145, 0) 100%);
display: flex;
align-items: center;
justify-content: center;
height: 100%;
>

.slider
width: 100%;
max-width: 600px;
height: 400px;
margin: 20px;
text-align: center;
border-radius: 20px;
position: relative;
>

slider-container can be anything — I’ve just used a flexbox to make it easy to centre the slider. But if you prefer, you can use CSS Grid (it’s a question of preferences, as we explained in this CSS Grid Vs. Flexbox article)

slider just sets the size of your slider — you can adjust this to suit your needs.

Next, we’ll style the slides element:

.slides  
display: flex;
overflow-x: scroll;
position: relative;
scroll-behavior: smooth;
scroll-snap-type: x mandatory;
>

OK, this is where the magic happens. If we set overflow-x to scroll, anything that doesn’t fit in our slider viewport will be accessible only by scrolling.

Setting scroll-behavior to smooth and scroll-snap-type to x mandatory means that if we jump-link to any child element of slides , the browser will scroll to it smoothly, rather than just jumping immediately to that element.

Right, next let’s style the slides themselves:

.slide:nth-of-type(even)  
background-color: rgb(250, 246, 212);
>

.slide
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
width: 100%;
height: 400px;
margin-right: 0px;
box-sizing: border-box;
background: white;
transform-origin: center center;
transform: scale(1);
scroll-snap-align: center;
>

.slide__text
font-size: 40px;
font-weight: bold;
font-family: sans-serif;
>

Match the size of slide to be the same as slider . The final three properties, transform-origin , transform , and scroll-snap-align , are key. These ensure that when we jump-link to any particular slide, the slide will ‘snap’ into the middle of the slider viewport.

If you click inside the slider, then press the arrow keys, you’ll see the smooth scrolling and snapping behaviour in action.

But of course we don’t want our users to have to do this! We want to put some navigation buttons on the slider instead — and we should probably get rid of that scrollbar too!

Step 2 — Adding the slider navigation buttons

In the HTML, I’ve added two a elements to each slide:

div class="slider-container"> 
div class="slider">
div class="slides">
div id="slides__1" class="slide">
span class="slide__text">1span>
a class="slide__prev" href="#slides__4" title="Next">a>
a class="slide__next" href="#slides__2" title="Next">a>
div>
div id="slides__2" class="slide">
span class="slide__text">2span>
a class="slide__prev" href="#slides__1" title="Prev">a>
a class="slide__next" href="#slides__3" title="Next">a>
div>
div id="slides__3" class="slide">
span class="slide__text">3span>
a class="slide__prev" href="#slides__2" title="Prev">a>
a class="slide__next" href="#slides__4" title="Next">a>
div>
div id="slides__4" class="slide">
span class="slide__text">4span>
a class="slide__prev" href="#slides__3" title="Prev">a>
a class="slide__next" href="#slides__1" title="Prev">a>
div>
div>
div>
div>
  • The one going backwards has the slide__prev class, and the one going forwards has the slide__next class.
  • the href contains the jump link to the slide we want to move to. You have to set these manually.
.slide a  
position: absolute;
top: 48%;
width: 35px;
height: 35px;
border: solid black;
border-width: 0 4px 4px 0;
padding: 3px;
box-sizing: border-box;
>

a.slide__prev
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
left: 5%;
>

a.slide__next
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
right: 5%;
>

You can style and position these buttons however you want — I’ve chosen to have arrows pointing in each direction. Sometimes the simple option is the best — but you can make your own choice!

Step 3 — Removing the scrollbar with CSS

.slider  
width: 600px;
height: 400px;
text-align: center;
border-radius: 20px;
overflow: hidden;
position: relative;
>

. just add overflow: hidden; to .slider . This also bring the border radius into play.

OK, pretty good — but ideally we don’t want the buttons to be locked to each slide. Sliders typically have buttons fixed in place.

But is that possible with CSS?

Step 4 — Fixing the navigation buttons in place

We don’t need to change the HTML for this, but we do need to update our CSS a bit:

.slide a  
background: none;
border: none;
>

a.slide__prev,
.slider::before

transform: rotate(135deg);
-webkit-transform: rotate(135deg);
left: 5%;
>

a.slide__next,
.slider::after

transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
right: 5%;
>

.slider::before,
.slider::after,
.slide__prev,
.slide__next

position: absolute;
top: 48%;
width: 35px;
height: 35px;
border: solid black;
border-width: 0 4px 4px 0;
padding: 3px;
box-sizing: border-box;
>

.slider::before,
.slider::after

content: '';
z-index: 1;
background: none;
pointer-events: none;
>

OK so what’s going on here? Well first, we’ve taken the background and border off of the a element. This makes our buttons effectively invisible.

Then, we’ve added before and after pseudo elements to slider . These have the same style that we previously had on the a elements — the nice simple arrow. And we’ve positioned them exactly on top of our now invisible buttons, and set pointer-events to none .

Because they are attached to the slider element and not slide , they will remain fixed in place as the user scrolls through the slides. But. when the user clicks on one, they are actually clicking on the invisible button attached to the actual slide.

This gives the illusion of fixed navigation buttons! Nice eh?

OK, now we’ve got a pretty good, pure CSS slider!

Aha, I hear you say, but what about breadcrumbs, can we add those too?

Glad you asked — yes we can!

Step 5 — Add breadcrumbs to the slider

To add the breadcrumbs to the slider, we are really using the same techniques we’ve just been through — just in a slightly different way.

Each breadcrumb will just be another jump link pointing to the relevant slide, and we’ll position it absolutely in the slider element.

So here’s the HTML (put this in slider , below the slides element):

div class="slider__nav"> 
a class="slider__navlink" href="#slides__1">a>
a class="slider__navlink" href="#slides__2">a>
a class="slider__navlink" href="#slides__3">a>
a class="slider__navlink" href="#slides__4">a>
div>

See? Same links as we used before. Now to style it:

.slider__nav  
box-sizing: border-box;
position: absolute;
bottom: 5%;
left: 50%;
width: 200px;
margin-left: -100px;
text-align: center;
>

.slider__navlink
display: inline-block;
height: 15px;
width: 15px;
border-radius: 50%;
background-color: black;
margin: 0 10px 0 10px;
>

Again, you are free to style these however your heart desires!

And here is the final result:

A pretty cool slider, and no JavaScript in sight. Hope that’s useful to you!

Conclusion

This is a useful trick that lets you create slider functionality — even for people with JS turned off. But of course, without JS, you’re really limited in what you’re able to do and how you can integrate it with your existing site.

If you wanted to harness the power of JS to create beautiful, responsive, full-page sliders, check out fullPage.js. It’s got slider functionality right out of the box, and includes support for:

  • Breadcrumb navigation — which you can move around and style easily
  • Autoplay — so your visitors get to see more of your awesome content even if they don’t click the navigation buttons!
  • Lazy loading — speed up your site by only loading assets when needed
  • Lots, lots more

It’s also super-easy to set up — so give it a try!

And if you still hungry for sliders, get inspired by this list of amazing animated sliders or this another one with cool Webflow sliders.

Warren Davies is a front end developer based in the UK.
You can find more from him at https://warrendavies.net

Join 2,000+ readers and learn something new every month!

Источник

Простой адаптивный текстовый слайдер Pure CSS

Добро пожаловать в учебное пособие о том, как создать простой адаптивный текстовый слайдер с использованием чистого CSS.

Надоели эти сложные слайды, требующие дополнительных библиотек? Почему бы не создать свой собственный?

Текстовые слайдеры Pure CSS на самом деле довольно просты, и это небольшое руководство поможет Вам создать простой слайдер текста – читайте дальше!

Адаптивный текстовый слайдер Pure CSS

Хорошо, давайте не будем лить много воды в статье, а сразу начнем с описания горизонтального текстового слайдера (который прокручивается справа налево).

HTML очень прост, просто разместите слайды между контейнерами.

Слайд 1

Здесь мы разместим наш первый слайд!

Слайд 2

Здесь будет описание второго CSS слайда.

Слайд 3

Ну а в этом месте напишем третий слайд.

Здесь приведу описание блоков , и какой блок за что отвечает в html коде слайдера.

 является основным контейнером, это “фиксированная видимая область на экране”. это “вторичный контейнер”, в котором мы будем применять анимацию CSS для сдвига слайдов. это отдельные слайды, которые будут вытеснены в длинный горизонтальный ряд с помощью CSS.

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

.hwrap < width: 100%; height: 150px; /* OPTIONAL */ background: #fffdea; border: 2px solid #ffcf1f; overflow: hidden; /* HIDE SCROLLBARS */ >.hmove < display: flex; position: relative; top: 0; right: 0; >.hslide < width: 100%; flex-shrink: 0; box-sizing: border-box; padding: 10px; >@keyframes slideh < 0% < right: 0; >33% < right: 100%; >66% < right: 200%; >100% < right: 0; >0% < right: 0; >30% < right: 0; >33% < right: 100%; >63% < right: 100%; >66% < right: 200%; >97% < right: 200%; >100% < right: 0; >> .hmove < animation: slideh linear 15s infinite; >.hmove:hover 

Это выглядит несколько необычно, но вся идея состоит в том, чтобы выложить стороны в горизонтальный ряд, а затем использовать анимацию CSS для их поворота.

.hwrap это фиксированная видимая область на экране. Важными частями здесь являются настройка размера с width: 100% помощью и использование overflow: hidden для скрытия уродливых полос прокрутки. Затем выложим все слайды в длинный горизонтальный ряд. Установим .hmove значение display: flex. width: 100% и flex-shrink: 0on .hslide ставит все слайды в одну строку.

Наконец, разберемся с движением слайда с помощью анимации CSS.

Установим .hmove значение position: relative – это необходимо для сдвига слайдов. Да, некоторые из вас, возможно, уже догадались – мы создаем последовательность @keyframesс разными right: N% для движения слайдов. Наконец, мы просто прикрепляем ключевые кадры .hmove, и это все.

ДОБАВЛЕНИЕ И УДАЛЕНИЕ СЛАЙДОВ Pure CSS

Как вы, возможно, уже видели, для добавления или удаления слайдов потребуется немного “вычислений”.

HTML - это не такая уж большая проблема, просто добавьте или удалите . Не очень удобная часть связана с CSS, где вам нужно будет обновить @keyframes slideh. Пересчитайте соответствующим @keyframes образом. Поэтому, если у вас всего 4 слайда, я рекомендую останавливаться на каждом 100% / 4 = 25%. Это: 0 - right: 0 25% - right: 100% 50% - right: 200% 75% - right: 300% 100% - right: 0 Затем просто добавьте промежуточные паузы. 20% - right: 0 45% - right: 100% 70% - right: 200% 95% - right: 300% Наконец, вы также можете настроить время анимации для ускорения или замедления – .hmove 

Картинка-пример работы нашего текстового слайдера. (Стрелки сюда не входят)

Простой текстовый слайдер CSS Простой текстовый слайдер CSSПростой текстовый слайдер CSS

Вот мы и закончили создание простого слайдера текста на CSS. Можете скачать CSS,HTML архивом.

Посетители, находящиеся в группе Гости, не могут оставлять комментарии к данной публикации.

Источник

Читайте также:  Web application index html
Оцените статью