Creating a simple, yet powerful, variable height content slider


Recently I looked for a simple way of doing a content slider for a web page on one of my side pet projects.

Having used some image sliders before (see Rich Bradshaw), I was under the impression that it would be a straight forward task.

Unfortunately it was quite hard since I was not able to find a simple, variable height, content slider that could be quickly adapted into a web page.

The problem with the typical image sliders is that they all rely on absolute positioning and therefore eliminating the possibility to have a simple variable height content slider.

The solution I came up with defines the following HTML structure:

HTML

<div class="viewportBox">
    <div class="viewportContainer">
        <div id="vpleft" class="viewport">Left Viewport</div>
        <div id="vpright" class="viewport">Right Viewport</div>
    </div>
</div>

As you can see, the structure is very simple and any variable content can be set in the viewport classed DIVs.

CSS

.viewportBox {
    background-color: red;
    width: 120px;
    overflow-x: hidden;
    margin-left:auto;
    margin-right:auto;
}

.viewportContainer {
    background-color: cyan;
    left: 0px;
    width: 220px;
    padding: 5px;
}

.viewport {
    position: relative;
    display: inline;
    background-color: azure;
    float: left;
    width: 100px;
    margin: 5px;
}

The CSS is also quite simple.

  1. viewportBox classed DIV:

    • width: sets the DIV width
    • overflow-x: set to hidden – this hides all content that goes over the width range

  2. viewportContainer classed DIV:

    • width: total with of the contained data = viewportBox width * number of viewports

  3. viewport classed DIV:

    • width: same as viewportBox
    • display: set to inline
    • position: set to relative
    • float: set to left

JavaScript/jQuery

$('.viewport').animate({
    left: "-=110px"
});

The script uses jQuery.animate() to translate all viewport classed DIVs to either left or right by the full column width size.

A fully working and interactive example can be found in here.

You can also play with it in jsfiddle.

In addition, you can also experience the final result in my pet project experience: Traits

Advertisements

About CrazyPenguin

Software Engineer
This entry was posted in CSS, CSS3, HTML5, JavaScript. Bookmark the permalink.

One Response to Creating a simple, yet powerful, variable height content slider

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s