Home / Articles / Programming languages / Markup languages / HTML & CSS / Creating an image slider using only CSS3 (without page scrolling)

Creating an image slider using only CSS3 (without page scrolling)

Creating an image slider using only CSS3 (without page scrolling)
 
Creating an image slider using only CSS3 (without page scrolling)
  • Currently 0 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 0/5 (0 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


This is improved version of the slider which was presented in the previous article.

The new version of the slider has only a couple of changes, so there is no need to describe the old slider code, only the changes. Here is the description of the old slider code: creating an image slider using only CSS3.

The current slider has three advantages in comparison with the old one:

  1. There is no page scrolling while clicking the navigation buttons.
  2. Now the default image also has full animation when you first time switch between images using navigation buttons.
  3. In HTML, one element was removed to make it simpler ("slide-frame" element).

To prevent page scrolling, the targeted elements were changed from img to div tags, where div elements are placed in the same parent element as img elements (here parent element is tag div with id "slides"). Every div element has its own neighbor - img element.

All div elements have two CSS properties:

  1. display with value none to hide all div elements. They don't need to be displayed, because they are only used for targeting by :targed selector.
  2. position with value fixed to turn off page scrolling. All elements with such position are positioned relative to the browser window, that is the reason why page scrolling stops working and that's what we wanted in the first place.

When div element is targeted by :target selector, the special CSS styles are applied to its neighboring img element which goes right after the current div element. That's the whole trick!

Here is a part of CSS code which is used to get the result:

#slides div {
  display: none;
  position: fixed;
}

#slides div:target + img {
  left: 0;
  z-index: 5;
  opacity: 1;
}

The following CSS code displays the default image with class "default" which has to be shown when none of the images hasn't yet been selected by the navigation buttons. Meanwhile, this CSS code hides the default image when one of images is selected by the navigation buttons.

#slides img.default {
  left: 0;
  z-index: 5;
  opacity: 1;
}

#slides div:target ~ img.default {
  z-index: 1;
  opacity: 0;
  left: -500px;
}

Here is the full HTML and CSS code for the new slider.

HTML code:

<div id="image-slider">
  <div id="slides">
    <div id="slide1"></div>
    <img src="nature1.jpg" alt="" />
    <div id="slide2"></div>
    <img src="nature2.jpg" alt="" />
    <div id="slide3"></div>
    <img src="nature3.jpg" alt="" />
    <div id="slide4"></div>
    <img src="nature4.jpg" alt="" />
    <div id="slide5"></div>
    <img src="nature5.jpg" alt="" />
    <img class="default" src="nature1.jpg" alt="" />
  </div>
  <div id="navigation">
    <a href="#slide1">1</a>
    <a href="#slide2">2</a>
    <a href="#slide3">3</a>
    <a href="#slide4">4</a>
    <a href="#slide5">5</a>
  </div>
</div>

CSS code:

#image-slider {
  margin: 100px auto;
  width: 500px;
}

#navigation {
  margin: 5px 0 0 0;
  text-align: center;
  z-index: 10;
}

#navigation a {
  text-decoration: none;
  background: #003C72;
  padding: 2px 6px;
  color: #FFFFFF;
  display: inline-block;
}

#navigation a:hover {
  background: #0182C4;
}

#slides {
  height: 375px;
  overflow: hidden;
  position: relative;
}

#slides img {
  position: absolute;
  top: 0;
  left: -500px;
}

#slides img {
  z-index: 1;
  opacity: 0;
  /* animation */
  transition: all linear 400ms;
  -o-transition: all linear 400ms;
  -moz-transition: all linear 400ms;
  -webkit-transition: all linear 400ms;
}

#slides div {
  display: none;
  position: fixed;
}

#slides div:target + img {
  left: 0;
  z-index: 5;
  opacity: 1;
}

#slides img.default {
  left: 0;
  z-index: 5;
  opacity: 1;
}

#slides div:target ~ img.default {
  z-index: 1;
  opacity: 0;
  left: -500px;
}

Live demo


 

Read also

Creating an image slider using only CSS3

Creating an image slider using only CSS3

CSS3: multiple backgrounds

CSS3: multiple backgrounds

Discussion (total 13 comments)

Tyler
September 24, 2013 at 06:47 pm
Is there a way to add captions to the slider that change with the images? If so, how?
Administrator User
Administrator User
September 25, 2013 at 06:40 am
Do you want to have a caption for each slide which should be displayed over the image in the bottom of the slide (for example with semi transparent background)?
Tyler
September 25, 2013 at 07:29 am
That wouldn't really work for the images I have... I'd prefer if the captions could be between the pictures and buttons. (On another note, is it possible that you could change the transitions to animations to make the image start and go though the images by itself, and then repeat when it's on the last image?)
Administrator User
Administrator User
September 26, 2013 at 04:22 am
The following changes need to be applied.
Change CSS selectors:
From #slides img to #slides div
From #slides div to #slides span
From #slides div:target + img to #slides span:target + div
From #slides img.default to #slides div.default
From #slides div:target ~ img.default to #slides span:target ~ div.default
Change the height of the slider from 375px to 405px:
#slides {
  height: 405px;
  ...
}
The height must be changed if the size of caption text is changed or in the case when caption text is in two rows. There is no way to figure out it automaticaly using only CSS.
Also add your own styles for captions:
#slides h3 {
  margin: 0;
  text-align: center;
}
HTML structure must be changed in the following way:
<div id="slides">
  <span id="slide1"></span>
  <div>
    <img src="nature1.jpg" alt="" />
    <h3>Simple caption 1!</h3>
  </div>
  <span id="slide2"></span>
  <div>
    <img src="nature2.jpg" alt="" />
    <h3>Simple caption 2!</h3>
  </div>
  ...
  <div class="default"><img src="nature1.jpg" alt="" /></div>
</div>
About your last question: it's not possible to do an automatic rotation of the slides using only CSS. To do this you will need to use JavaScript.
Veronika
December 03, 2013 at 02:39 am
Thank you!

I have been searching for this whole morning, and its EXELENT! As am just the begginer for this things ;)

Thank you thank you!
Kim
June 10, 2014 at 08:02 am
I had to add the following to see my pictures

img {
    zoom: 0.15;
}
Administrator User
Administrator User
June 10, 2014 at 09:18 am
Very strange! Which version of browser do you use?
miguel antonio gomez heichard
June 25, 2015 at 04:40 pm
Muito bom, brigadão.
EdwardhoilM
January 20, 2017 at 04:31 pm
<a href=http://kupikvadrik.ru/>купить детский квадроцикл</a>
WilliamRus
January 22, 2017 at 09:16 pm
<a href=http://shemale-sex.net/tier/solo/shemaleview1.html>shemale solo</a> - shemale anal sex, big tits shemale.
Robertthund
February 03, 2017 at 03:53 am
<a href=https://mrwhite.biz/>cc shop</a> - sell dumps, carding forums.
RobertAcous
February 08, 2017 at 03:39 pm
excellent web site <a href=http://sexfreevideos.net/>http://sexfreevideos.net/</a>
WilliamRop
February 11, 2017 at 10:27 am
КАРТИНЫ НА СТЕКЛЕ! На заказ!

УЗНАТЬ ПОДРОБНЕЕ/ЗАКАЗАТЬ - http://tinyurl.com/kartinu-na-stekle

Картины, панно и модульные картины выполненны на стекле по технике УФ-печати.
Материал – закаленное стекло 5 мм с нанесением противоосколочной пленки, с обработкой по периметру и удобной системой креплений.
Выполним заказы на картины и панно по Вашим фотографиям и изображениям, репродукции картин известных художников.
Максимальный размер 1500мм. по одной стороне.
Обеспечим доставку в любой регион через транспортные компании.
Нанесение изображения на стекло, оргстекло, пенокартон, монолитный поликарбонат, ЛДСП, ЛМДФ, мебельные фасады, металл по технологии УФ печать.

УЗНАТЬ ПОДРОБНЕЕ/ЗАКАЗАТЬ - http://tinyurl.com/kartinu-na-stekle

рамка +для картины купить киев, инфракрасные обогреватели картины купить, где купить картину +в липецке, купить белые модульные картины, картины маслом купить украина, купить картину краснодаре недорого, картины маслом цветы купить, модульные картины купить +в харькове цена, купить паспарту +для картины +в интернет магазине, фотообои картина купить, крепление +для модульных картин купить, картины +для интерьера купить +в интернет магазине, купить картину +в витебске, картина поцелуй купить, картины бисером москве купить

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation