Are you looking to hire a designer? Post a job listing on our design job board. Visit the design job board.

Easy Display Switch with CSS and jQuery

Today, I would like to go over a quick and simple way to allow your users to switch page layouts by using CSS and jQuery.

Today’s web users expect web pages to be increasingly more interactive. To this end, the ability to change page layouts provides your users with a more immersive experience and allows them to consume information more easily, either with a quick gallery view, or a detailed summary view.

View Demo of Display Switch

Display Switch Sample

Step1. Creating the Wireframe

We will first start out designing the vertical list layout with a simple unordered list which we will use as our columns/rows.

HTML

<ul class="display">
    <li></li>
    <li></li>
    <li></li>
</ul>

CSS
*Note I used different shades of grey to achieve the subtle bevel look.

ul.display li a {
    color: #e7ff61;
    text-decoration: none;
}
ul.display li .content_block {
    padding: 0 10px;
}
ul.display li .content_block h2 {
    margin: 0;
    padding: 5px;
    font-weight: normal;
    font-size: 1.7em;
}
ul.display li .content_block p {
    margin: 0;
    padding: 5px 5px 5px 245px;  /*--The left padding keeps the
content from flowing under the image--*/

    font-size: 1.2em;
}
ul.display li .content_block a img{ /*--Double border technique--*/
    padding: 5px;
    border: 2px solid #ccc;
    background: #fff;
    margin: 0 15px 0 0;
    float: left;
}

Step2. Styling the Content

Inside of each list item, we nest a div which will act as our container of the content inside. I feel it’s easier to calculate the columns when you don’t have to consider the margin and padding within. This comes in handy especially when you are working with a liquid layout (since we know % and fixed pixels don’t mix in too well).

HTML

<li>
        <div class="content_block">
            <a href="#"><img src="sample.gif" alt="" /></a>
            <h2><a href="#">Image Name</a></h2>
            <p>Description goes here</p>
        </div>
    </li>

CSS

ul.display li a {
    color: #e7ff61;
    text-decoration: none;
}
ul.display li .content_block {
    padding: 0 10px;
}
ul.display li .content_block h2 {
    margin: 0;
    padding: 5px;
    font-weight: normal;
    font-size: 1.7em;
}
ul.display li .content_block p {
    margin: 0;
    padding: 5px 5px 5px 245px;  <span style="color: #777;">/*--The left padding keeps the
content from flowing under the image--*/
</span>
    font-size: 1.2em;
}
ul.display li .content_block a img{ <span style="color: #777;">/*--Double border technique--*/</span>
    padding: 5px;
    border: 2px solid #ccc;
    background: #fff;
    margin: 0 15px 0 0;
    float: left;
}

Step3. Creating the Secondary View Option

Now its time to style the second display option which are in columns flowing horizontally.

Adding jQuery

CSS

ul.thumb_view li{ width: 250px; } <span style="color: #777;">/*--Switch the width
to accommodate for the three column layout--*/
</span>
ul.thumb_view li h2 { display: inline; }
ul.thumb_view li p{ display: none; }
ul.thumb_view li .content_block a img { margin: 0 0 10px; }

Step4. Creating the Switch

Time to wrap up this tutorial by creating the switch.

Switch Button

HTML

<a href="#" class="switch_thumb">Switch Display</a>

CSS
Using the ‘CSS Sprites’ technique, I create the link button.

a.switch_thumb {
    width: 122px;
    height: 26px;
    line-height: 26px;
    padding: 0;
    margin: 10px 0;
    display: block;
    background: url(switch.gif) no-repeat;
    outline: none;
    text-indent: -9999px;
}
a.swap { background-position: left bottom; }

I didn’t feel like creating a hover state on the image, so I’ll just use the opacity to dim it down a tad bit once hovered over.

a:hover.switch_thumb {
    filter:alpha(opacity=75);
    opacity:.75;
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
}

jQuery
At last, we’ll activate the switch with a little bit of jQuery.

<script type="text/javascript">
$(document).ready(function(){

    $("a.switch_thumb").toggle(function(){
        $(this).addClass("swap");
        $("ul.display").fadeOut("fast", function() {
            $(this).fadeIn("fast").addClass("thumb_view");
        });
    }, function () {
        $(this).removeClass("swap");
        $("ul.display").fadeOut("fast", function() {
            $(this).fadeIn("fast").removeClass("thumb_view");
        });
    });

});
</script>

Final View

View Demo of Display Switch

Display Switch Sample

Now Go and Experiment!

This method can be applied to many scenarios, so I would like to encourage you to experiment with this technique. If you have any other tricks to add on, please feel free to drop your comments!

About the Author:

Soh Tanaka is a Web Designer and blogger from Los Angeles. For more front-end web development tutorials, check out his blog or you can follow him on twitter @SohTanaka

148 Responses from Readers

Jesse Foster March 9th, 2009

Very nice. Simple technique with excellent results.

Good job.

Will March 9th, 2009

Very impressive; I’m not exactly sure how I will implement this yet, but I’ll let you know!

Jad Limcaco March 9th, 2009

This is an awesome tutorial. Thank you and I will definitely be using this.

Tracey Grady March 9th, 2009

Nice effect, Soh. I just wonder how it looks to a site visitor who has javascript turned off?

Where possible I think it’s important to use javascript functions which degrade gracefully, and if this does so then that would be doubly useful.

Tom March 9th, 2009

MMMMMMMMMMMM

Nice!!

Jean-Baptiste Jung March 9th, 2009

Excellent tutorial! I definitely should implement it on one of my blogs!

DamirK March 9th, 2009

Nice…

joyoge designers' bookmark March 9th, 2009

nice work, thanks for the helpful tut..

Bruno March 9th, 2009

Great tut!
It´ll help a lot my recent project!

Jacob Gube March 9th, 2009

Great tutorial Soh!

Sérgio Soares March 9th, 2009

awesome work :)

theBagg March 10th, 2009

Just a little bug if you double click the switch view button. The views get mixed up.

cougar March 10th, 2009

That’s cooooool.

Mike Mella March 10th, 2009

Tracey Grady’s right. Graceful degradation is important, and this does not accommodate that.

Looks cool otherwise though.

sky March 10th, 2009

wow..it’s so cool bro..

thank u for your post..

Wireframing Tools March 10th, 2009

i got the same thing as theBagg.

Branden Silva March 10th, 2009

How hard would it be to add pagination into this? I love the effect and would love to have 3 different display types, along with pagination to reduce the load times of a million images.

izzat aziz March 10th, 2009

never thought it actually that simple.
i think it gonna use some crazy java
code, but nope. it just that..

thanks.

Neon March 10th, 2009

Fantastic! Such a simple idea and simple code too for a fabulous result.

noelmcg March 10th, 2009

great tutorial cheers

Vini March 10th, 2009

This is a simple but awesome thing! Congratulations!

Bill Lowden March 10th, 2009

Very nice, and the code is well documented and easy to follow. Thanks.

François March 10th, 2009

Thanks a lot! Wonderful piece of code!
It will be useful for my future projects!!!

Soh Tanaka March 10th, 2009

Thank you all for the comments, Im glad that you guys liked it. Looking forward to seeing some nice stuff with this technique :-)

@Tracey Grady, @Mike Mella, when javascript is turned off, there is nothing hindering the user from the content since all we are doing is showing them less info when the button is clicked. To make the button not appear when js is turned off, we can simply add a “display: none;” on the button, and .show() once jquery is done loading :-)

@theBagg, @WireframingTools, can you please let me know which browser had the buggy issue? I was trying to make it skip but I wasn’t able to pull it off.

Thank you again!~

evertt de sousa March 10th, 2009

Incredible :) Very nice

thank you

Timothy March 10th, 2009

Pretty slick

Craig March 10th, 2009

It’s great to see how easy such an elegant effect can be coded. Thanks gor the tutorial.

Chris Casarez March 10th, 2009

Well written and easy enough for a CSS layman to follow!

Nokadota March 11th, 2009

This would be great for a gallery, thanks for the tut Sol.

Brian Wilcox March 11th, 2009

I was looking for a nice way to promote some category thumbnails with different variations.

I just found it! Nice work Tanaka.

Jens March 11th, 2009

Who have javascript turned off these days :) ?

I whould sure use it!

stack March 11th, 2009

nice but you miss one point
another switch to the real size of the image would be great
as i got my own portfolio with thumbnail, normal size and big size

and no i dont want another lightbox for big size
only jquery rocks !!

;)

Mendoza Opina March 11th, 2009

nice!!! :)

Jean March 11th, 2009

No cookie to remember witch layout was last used?
Quite useless…

George March 11th, 2009

Soh,
Good stuff – helpful to many!

Komang March 11th, 2009

Great! simple but excellent result

David D March 12th, 2009

Very nice.
I’m going to have to learn me some jquery.

Layout works fine with javascript disabled, but none of the switching works. That doesn’t seem to be a problem for anyplace that I would use this.

Frank March 12th, 2009

Very nice!

Would be good to add a cookie to remember the last layout.

How would you invert the process from thumb view to list?

thanks!

Martin Sarsini March 12th, 2009

Simply beautiful!

xene March 12th, 2009

useful tutorial. Thanks a lot

Soh Tanaka March 12th, 2009

Hey guys, I’m looking into the cookie issue, I had this in mind when making this tutorial so it was actually intended for a smaller site w/out paging. But to make this useful for sites of all sizes, its a must~

@Frank, If you want to reverse the order, your going to have to set the default list style to have the thumbs first, and in your jquery, your going to addClass your list style to the thumb layout. Also don’t forget to change the css sprites on the button as well~

Steph March 12th, 2009

OMG, I want to use this! It’s so snazzy! Thanks.

Igor March 13th, 2009

Very nice and simple! thank you!

xavo March 14th, 2009

mmm.. good idea!!

Joefrey March 16th, 2009

Great Tutorial! I’m gonna surely use this this technique! Thanks for sharing!

Joefrey March 16th, 2009

Can you try to use cookie on this? Like on the bestwebgallery style. Because everytime I open the demo it will back to the default style.

SB March 16th, 2009

nice

David D March 16th, 2009

Well, it’s a 94% solution for me.

It works great in Firefox and Explorer. But it looks like the switching part is broken in Chrome and Safari. The content_block DIVs have the correct width, but they end up being a narrow list on the left side of the page.

I’ll still use it on a personal site, but even with only 6% Safari users, I can’t use this on one of my ecommerce sites.

solona March 17th, 2009

Nice!

Owl March 17th, 2009

Will work perfectly on my webshop =)

Jhon Doe March 23rd, 2009

good job!!

fonso gfx March 30th, 2009

Great tutorial.:)

Allie March 30th, 2009

Awesome tutorial, I’ve been looking for something like this :D

Franky March 30th, 2009

Hi there,

First off all, very nice trick with css and jquery.
I do have a question though. Would it be possible (easy) to add a “third” display option?

I am very new to jquery and wouldnt exactly know if toggle could accomplish what i am looking for.

Hope to hear from you.

Thanks!

samir March 30th, 2009

Great idea, thanks for the tip.

modja April 6th, 2009

this very cool, thx for share

wallan April 13th, 2009

Man you know how to make a good tutorial. Great

sonvm April 17th, 2009

Thanks for share ! I like this :-)

erw13n April 19th, 2009

Wow, never though that Tabs can use like this.
Nice idea

Barbaros Alp April 20th, 2009

Good idea, great.

ArranM April 30th, 2009

Very nice, i would think about adding a cookie, so it remembers your switch view for the next time you visit.

thanks for sharing.

בניית אתרים April 30th, 2009

Very nice mate keep Up…
its possible to start with the thumb_view (2)
10X mate

Setiaji May 8th, 2009

Thank you so much, this tutorial give me some idea..!!

Thank you..

GreyK50 June 22nd, 2009

Awesome Tuts Soh, thanks for sharing this.

lee June 25th, 2009

Great script; can think of many uses.

But: is there a way to stop it from jumping to the top of the page when one clicks the switch?

Nick June 25th, 2009

Soh, Were you ever going to get it working with a cookie? That would be really appreciated.

Alcor July 6th, 2009

Awesome script. Thanks for sharing.

Josh July 22nd, 2009

Pretty freakin’ sweet! I put this tutorial to good use at 83themes.com. Thanks for making it so easy!

Dax Hansen July 31st, 2009

Thank you so much, that’s an awesome gallery! So fresh and so clean, clean.

WAMPvn August 1st, 2009

been searching all over Google for a non-complicated way to add reviews and ratings and it looks like this is it.

Thank you a million times over.

Rihanna Lee August 12th, 2009

Did any one ever figure out how to keep the page from jumping back to the top of the site? – Rihanna

martin.cui August 12th, 2009

Very Nice,It is a good job!!!

SP August 12th, 2009

Very very cool!

I have been trying and trying to get the cookie to work because I have multiple pages but just can’t get it. Did ANYONE get a working version with a saved cookie?

Website Design Services August 13th, 2009

That is a great display switch plugin! I might have to use this with a project I am working on (:

Annette August 13th, 2009

I’m also running into a page jump problem. I tried to replace the “#” hashes with a…

onclick=”return false;”

… but that doesn’t fix the issue. Any idea?

A URL example is available by clicking my name link.

Flow August 19th, 2009

Can someone tell me how i can use that gallery seperately twice or more often on one site?
So that i can have different categories and when i change the display method of one category only this one changes and not all on the site.

DevNet September 3rd, 2009

Nice. The good thing is that its simple and easy to read for anyone!

Egypt Web design company September 9th, 2009

Very Nice,It is a good job!!!
thanks so much

Andrew October 19th, 2009

Great tutorial. Thanks for taking the time to write this!

Ronald Nunez October 21st, 2009

I’ll use this on one of my projects. this is very helpful, thanks for sharing your knowledge

Steve October 24th, 2009

Cool, this is excellent. I will definately be using it on my site…..

designfollow October 29th, 2009

thanks for this great tutorial.

sivakumar October 31st, 2009

we can use this for wallpaper websites… or photo sharing websites…But we should store this in database

Alexander November 13th, 2009

nice one, even tho a cookie is missing ;)

Marc November 17th, 2009

Hi this is very nice. I have everything working except the image for the switch doesn’t show. The spot is a hot spot and toggles but for some reason I can’t get the switch.gif to show up any suggestions?
thanks

Nox November 20th, 2009

Hello,
great tut!
Can someone tell me how i can show the thumb gallery first?
thx

Evan Smith November 24th, 2009

When you’re thinking about graceful degradation, you have to think, “Is this functional and usable to everyone?” So with consideration to javascript and the Switching Views, I’d say this degrades gracefully… it’s layout is still semantic XHTML with CSS. There’s only one catch. If javascript is not available to the user viewing this, they still see the list of items/images, they just don’t have the added feature available to switch views. So a tweak to this solution would be to write the switch_view div using javascript, so that if js isn’t available, then the user won’t even see the option to switch views. Otherwise… if you absolutely must have this necessary feature that degrades gracefully and all that marketing hype you scanned over on alistapart, you would have to work it in using some server side language to control the styles (which would require a page reload at least once until the option is set).

Mark November 28th, 2009

If you want to prevent it from causing the page to jump to the top, remove the hyperlink and use span instead.

Master cleanse weight loss December 22nd, 2009

Nice One. Very Appreciative.

It helped me save a lot of time and effort with the readymade coding posted here.

Sam December 27th, 2009

You can simplify this script using the ‘toggleClass’ function in jQuery:

$(“span.switch_thumb”).click(function () {
$(“span.switch_thumb”).toggleClass(“swap”);
$(“ul.display”).fadeOut(“fast”, function() {
$(this).fadeIn(“fast”).toggleClass(“thumb_view”);
});
});

Also, if you want to use a cookie to remember the view state, use the jQuery cookie plugin (http://www.stilbuero.de/index.php?PHPSESSID=09n8bbbakpkaamhk6hirk168f6&s=cookie&x=0&y=0), and then add to your code like this:

$(“span.switch_thumb”).click(function () {
$(“span.switch_thumb”).toggleClass(“swap”);
$(“ul.display”).fadeOut(“fast”, function() {
$(this).fadeIn(“fast”).toggleClass(“thumb_view”);
});
$.cookie(‘view_State’, $(‘ul.display’).is(‘.thumb_view’) ? ‘list’ : ‘thumbs’ );
});
// COOKIES
// view state
var view_State = $.cookie(‘view_State’);
// Set the user’s selection for the viewState
if (view_State == ‘thumbs’) {
$(“ul.display”).addClass(“thumb_view”);
$(“span.switch_thumb”).addClass(“swap”);
};

Jared January 2nd, 2010

Any restrictions on usage? Can I put this into my templates that I distribute and or sell? I build WordPress themes.

Steven Snell January 2nd, 2010

Jared,
Feel free to use it in your templates or themes.

Justin January 22nd, 2010

This is a great tutorial, I’m a big fan of your work mr. Tanaka, thank you for putting time back into the community. You can see my working version of this scrip on my blog: domeprojects.com Thanks again.

Trackbacks

Leave a Reply