CSS: styling a content slider

Many tutorials on jQuery and JavaScript teach you how to make a content slider work. In this post, I'm going to show you how to stylize a content slider with CSS to get it ready for being animated with jQuery or JavaScript. First of all, since most jQuery plugins use unordered lists as content sliders, I'm going to use an unordered list too.

Here's our basic markup:

<div id="slider-container">

<ul id="slider">

  <li id="slider-left"></li>
  
  <li id="slider-center"></li>
  
  <li id="slider-right"></li>

</ul>

<ul id="slider-controls">

    <li id="prev"><a href="#"><</a></li>
    <li id="next"><a href="#">></a></li>

</ul>

</div> 

We're going to insert also the slider controls, so I did create another list for that purpose. Our CSS will be:

body {
  margin: 0;
  padding: 3em 0;
  overflow-x: hidden;
  font-family: Arial, sans-serif;
  
}

#slider-container {
  width: 100%;
  height: 500px;
  position: relative;
}

#slider {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  list-style: none;
  position: relative;
}

#slider li {
    width: 500px;
    height: 500px;
    background: silver;
    position: absolute;
}

#slider-left {
    top: 0;
    left: -400px;
}
#slider-center {
   top: 0;
   left: 50%;
   margin-left: -250px;
}
#slider-right {
    top: 0;
    right: -400px;
}

#slider-controls {
    width: 536px;
    height: 20px;
    list-style: none;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -10px 0 0 -268px;
}

#slider-controls li {
   width: 20px;
   height: 20px;
}

#slider-controls #prev {
  float: left;
}
#slider-controls #next {float: right;}

#slider-controls a {
    display: block;
    float: left;
    width: 100%;
    height: 100%;
    line-height: 20px;
    text-align: center;
    font-weight: bold;
    color: #fff;
    background: #d40;
    text-decoration: none;
    border-radius: 6px;
}

We use contextual absolute positioning to place the slides in the correct order. Further, also our slider controls will be absolutely positioned but with a larger width so that they will not overlap with the main slide. Each slide is 500 pixels wide, so our controls container will be a little bit wider. Note that we've specified overflow-x: hidden on the body element to prevent browsers from showing any unnecessary scrollbar.

Here's how it looks like in IE6:

This horizontal scrollbar can be easily fixed by adding an overflow declaration where appropriate.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.