Как создать слайдер изображений или слайд-шоу
Слайдер изображений — это отличный способ отображения различных изображений веб-страницы. Красивые и интересные изображения могут привлечь много посетителей на вашу веб-страницу.
Обычно слайдеры изображений создаются с помощью JavaScript, но с версией CSS3 стало возможно создать слайдеры, используя только CSS3. В этой статье вы научитесь, как можно получить эффект слайд-шоу, сохраняя минимальный код CSS, а во второй части статьи вы узнаете, как создать слайдеры изображений с помощью JavaScript.
Создание слайдеров изображений используя только CSS3
Наверно вы уже видели слайдеры, созданные с помощью JavaScript, которые очень тяжело загружаются. Они замедляют работу веб-страницы, а также могут не работать, если пользователь отключил интерпретацию JavaScript в браузере. Одно из решений этой проблеме — это отказ от их использования, но как же можно создать слайдеры без использования JavaScript? Здесь вы найдете ответ.
How To Build an Image Slider From Scratch in HTML/CSS/JS
Want to build an image slider from scratch to use in any website?
In this tutorial you will learn how to build a simple website that displays a slideshow of images. This code isn’t perfect but I recently used this method to make a super fast slideshow without having to use anything more than a basic js file, and 56 high res images. This method loads one image at a time based on user input, and if you follow this tutorial, at the end you should have a fully functioning slideshow with super basic design, and the knowledge to implement it into your own website!
You can find all of the code on GitHub!
First things first, go ahead and setup a new folder. I’m gonna call mine “img-slider,” but you can call yours whatever you want.
Next add 3 more folders to that one called “js”, “css”, and “img”
Go ahead and open that first folder in the text editor of your choice, I use Sublime Text, and make a new file called index.html at the root of your project
next create a “style.css” file in the css folder, and an “init.js” file in the js folder
Now, you should have a project that looks something like this:
So, lets go ahead and get some basic code into that “index.html” file:
Now, go ahead and add your images to the img folder, it doesn’t matter how many, what size, or what format, but the naming is very important.
For this to work you need to rename all the images like this:
Now, lets link one of those images and check that everything’s working so far!
Next, open that index.html file in your web browser and you should see something like this:
Now its time for the javascript, the first thing to do is setup an array containing the img names, since we want to start at 1 the first name will be “null”, the second: “img_1.jpeg” and so on. I will be using 4 random images from the internet that all happen to be JPEG’s but that isn’t necessary. If you didn’t rename your images as described earlier, please do so now.
So, in your “init.js” file setup a function that will handle the slider operation:
This function is going to get passed a value “n” as a parameter, this is how we will tell it whether to go the next slide, or previous slide using 1 or 0 respectively.
Basically, the function slide is going to find the image in the site using jQuery, and then modify its SRC to display the next image.
To do this we will need to first get the image name from the SRC and split it to get a number from that image name, then depending on user input and our position in the list we will either go forward or backward in the list(increasing or decreasing the number in the image name), then with our new number we will rebuild the new image’s filepath and insert it into the html code, changing the displayed image to the new one.
To make things easier later we are going to store the image’s name using a variable like so:
This new line of code is going to find the image, and get its image name from the filepath, it then will separate the “img_” from our image name leaving us with a number and extension that gets stored in the variable imgName. For the first image in a folder it would go from “img_1.jpeg” to “1.jpeg”
With that ready to go we can start writing the logic for this function. Since we will either be going to the prev image or the next one we will need an if/else statement here to test whether n is equal to 0 or 1. In our html code we will then have buttons with onclick functions corresponding to these values, but we’ll worry about that later.
For now, create a simple if/else statement to test the value of n:
First let’s build the logic for going to the previous slide, we need to make sure that if we’re on the first image, that we don’t try to go to img_0 since it doesn’t exist, so first we have to see if we’re on the first image. Add this to your code:
imgName is storing the value “1.jpeg” for our first image, so if we split that and target the ‘.’ we can get an array containing [“1”, “jpeg”]
This code is getting an integer value from the first element in our newly created array, which will grab a numerical value of 1. seeing as we’re on the first image we will fail this test and the program will move to the else portion.
Lets get to work on that part now. This is the whole brains of the operation here, where we actually change the current image to a new one. First we need to access the image in the DOM using the same code from earlier:
Once the program has grabbed this object, we are going to change it with our new data. Currently, in the html code what we’re grabbing above looks like this: “<img src=”img/img_1.jpeg”>”
The data stored in imgName would look like
So, we want to replace the outerHTML of this image with an updated version of the string containing our new information. to go to the previous image, if we’re starting on 1, we would want to get to 4. In html we want our end result to look like this: “<img src=”img/img_4.jpeg”>”
To make that line of code we’re going to need the first element of the imgName variable for most of the html code, which we will combine with our new image’s name. The new image’s name will be pulled from the array we created earlier called imgNames. First we will get the numerical value of the current image’s postition in the list, in our case it’s 1. To go the previous slide we want to go to image 4, so we will add 3 to the index if we’re on image 1 and click on the “previous” button. The code for all of that will look like this:
imgName[0] + imgNames[parseInt(imgName[1].split(‘.’)[0]) + 3] + “\”>”;
This will get us the proper image.
Add this to your code:
$(‘div#slider.slider img.slider-img’)[0].outerHTML = imgName[0] + imgNames[parseInt(imgName[1].split(‘.’)[0]) + 3] + “\”>”;
This red arrow shows where it should go:
Now, copy that same line of code into the if portion:
If you remember from earlier, we are building the “previous slide” logic when starting on the first slide, that was difficult but you did it! Hooray! Now we need to build the “previous slide” logic for when you’re not on the first slide. Thats the code you just copied for a second time, depicted in Figure 1, and instead of adding 3(since were not at the first slide) all we want is to subtract 1. Towards the end of that line of code(circled in red above) you want to change it from + 3 to — 1 so that when you’re on img_2 it will go back to img_1.
Great! The hard part is over. Now we just need to copy that same logic into the else statement for when we want to go to the next slide, copy the contents of the blue area into the red area in your own code:
Now, since this part of our code handle the “Next Slide” logic we actually want the opposite effect as we have above. To achieve this, its very simple. Instead of testing to see if we are on the first slide, we need to test for the last slide, on Line 12 in Figure 2 you will see the code tests for equivalence to 4, if you have 56 images in your folder, that 4 should be a 56. Next, instead of SUBTRACTING one on Line 13(Fig. 2) you will want to ADD one, and instead of ADDING 3 on Line 15(Fig. 2) you will want to SUBTRACT 3.
You may be wondering where the “3” in my code comes from. That number needs to be equal to the total number of images in your folder minus 1. If you have 56 images, that number needs to be 55.
Alas, the nasty javascript hacking is complete. Time to add functionality to our HTML page with two simple buttons utilizing onClick Functions, like so:
Now, refresh that browser window where you tested the image before, and you should get something like this
Как сделать слайдер в HTML на своем сайте: краткая инструкция
Слайдер — это специальный веб — дизайнерский элемент, который представляет собой блок, внутри которого размещаются чередующиеся изображения, текст, видео и др. контент.
Слайдер в том или ином исполнении присутствует во всех современных веб-сайтах, потому что такие блоки являются визуально привлекательными и могут акцентировать внимание пользователей на своем контенте.
Слайдер для сайта — это норма
-
ручное и автоматическое перелистывание;
-
возможность перейти по ссылке, нажав на сам слайдер;
-
наличие кнопок с призывом действия;
-
анимационные эффекты при смене слайдов;
-
и мн. др.
-
за место, где вывести слайдер , отвечал HTML;
-
за то , как визуально выглядит слайдер , отвечал CSS;
-
за анимационные сценарии и дополнительные функции отвечал JavaScript.
Как реализовать слайдер для своего сайта
-
воспользоваться готовым решением, если это позволяет сделать ваш сайт;
-
сделать слайдер на сайте самостоятельно, например , применяя HTML и CSS.
Г отовое решение слайдера для сайта
-
установить соответствующий плагин из официального репозитория вашей CMS;
-
активировать плагин;
-
настроить слайдер в админке вашего сайта, добавив в него контент для вывода;
-
вывести слайдер в нужном месте при помощи шорткода, кода HTML или функции.
Как сделать слайдер на своем сайте HTML при помощи CSS
Бывает же такое, что сайт не использует CMS. В этом случае нужно будет самостоятельно разработать свой слайдер. Как правило, такая разработка слайдера должна быть осуществлена при помощи той же технологии, на которой разработан ваш сайт. Практически любой современный язык программирования или какой-либо фреймворк име ю т в своем арсенале инструменты для разработки слайдера. Все инструменты и подходы, как можно реализовать слайдер для сайта , не перечислить. Но мы можем рассмотреть самую простую ситуацию, как сделать слайдер на своем сайте HTML при помощи CSS.
Делаем простой адаптивный слайдер на CSS
Для начала нам нужен будет HTML слайдера. Например, у нас есть:
<body>
<div >
<input type=»radio» name=»kadoves» checked>
<input type=»radio» name=»kadoves» >
<input type=»radio» name=»kadoves» >
<div >
<label for=»slaid1″></label>
<label for=»slaid2″></label>
<label for=»slaid3″></label>
</div>
<div >
<div >
<img src=»https://codernet.ru/articles/web/kak_sdelat_slajder_v_html_na_svoem_sajte_kratkaya_instrukcziya/img1.jpg»/>
<img src=»https://codernet.ru/articles/web/kak_sdelat_slajder_v_html_na_svoem_sajte_kratkaya_instrukcziya/img2.jpg»/>
<img src=»https://codernet.ru/articles/web/kak_sdelat_slajder_v_html_na_svoem_sajte_kratkaya_instrukcziya/img3.jpg»/>
</div>
</div>
</div>
</body>
Чтобы все заработало как надо, необходимо добавить следующий CSS:
.adaptivSlayder <
position: relative;
max-width: 710px;
margin: 65px auto;
box-shadow: 0 9px 18px -4px rgba(0, 0, 0, 0.69);
>
.adaptivSlayder input[name=»kadoves»] <
display: none;
>
.kadoves <
position: absolute;
left: 0;
bottom: -35px;
text-align: center;
width: 100%;
>
.kadoves label <
display: inline-block;
width: 7px;
height: 7px;
cursor: pointer;
margin: 0 2px;
box-shadow: 0 0 3px 0 rgba(0, 0, 0, .7);
border-radius: 55%;
border: 4px solid #2f363c;
background-color: #738290;
>
#slaid1:checked
.kadoves label[for=»slaid1″] <
background-color: white;
>
#slaid2:checked
.kadoves label[for=»slaid2″] <
background-color: white;
>
#slaid3:checked
.kadoves label[for=»slaid3″] <
background-color: white;
>
.adaptivSlayderlasekun <
overflow: hidden;
>
.abusteku-deagulus <
display: flex;
width: 100%;
transition: all 0.6s;
>
.abusteku-deagulus img <
width: 100%;
flex-shrink:0;
>
#slaid1:checked
adaptivSlayderlasekun abusteku-deagulus <
transform: translate(0);
>
#slaid2:checked
.adaptivSlayderlasekun .abusteku-deagulus <
transform: translateX(-100%);
>
#slaid3:checked
.adaptivSlayderlasekun .abusteku-deagulus <
transform: translateX(-200%);
>
В CSS показан общий принцип реализации слайдера. Вы смело можете писать туда свои значения, чтобы слайдер «как родной» вписался в ваш проект.
Заключение
Слайдер — это способ задержать внимание посетителя вашего ресурса, поэтому если дизайн вашего сайта позволяет использовать слайдер, то почему бы этим не воспользоваться. Тем более что реализовать слайдер можно на чистом CSS и HTML.
Мы будем очень благодарны
если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.
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:
Read on to find out how.
Step 1 — create your slider layout
First you need to create a space for your slider to go into, and of course, some slides!
So here we have:
- 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.
Then we need the CSS:
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:
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:
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.
OK, so far we have this:
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:
- 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.
Now for the css:
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
. just add overflow: hidden; to .slider . This also bring the border radius into play.
That gives us this:
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:
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?
It looks like this:
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):
See? Same links as we used before. Now to style it:
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.
Related articles
About the author:
Warren Davies is a front end developer based in the UK.
You can find more from him at https://warrendavies.net

report this ad