Monday, April 12, 2010

Making an Image Gallery with :target

One of the selectors new to CSS3 is the :target pseudo-class, which can be used to apply rules to an element with a fragment identifier; that is, an anchor name or an id. For example, let’s assume you have a section heading with an id of ‘chapter_2′:

The Title of the Chapter

You could create a direct link to that element by using the fragment identifier at the end of the URL:

http://www.example.com/index.html#chapter_2

And, with the :target selector, apply a background to that element to indicate clearly where you have arrived:

h3:target { background-color: #ff0; }

Pretty useful, right? Not a killer feature, but useful nonetheless. It can be made even more useful, however, with a little bit of ingenuity; how about, for example, a pure CSS image gallery?

Take a look at this example (in a browser which supports :target; Mozilla, Webkit or Opera browsers will do the trick). Clicking the links allows you to browse through the different images, and it’s done with minimal markup and no scripting.

The first step is to create a list, with the image, name, and link in each list item; for example:

  • One

  • Each list item needs an id, which will provide the anchor, and the link href is to its own id; this allows :target to work its magic! All the images are absolutely positioned on top of each other, and using the selector simply changes the z-index value so the targeted image is on top:

    img { position: absolute; } li:target img { z-index: 100; }

    Easy! Of course, this is only a very simple example; with even more ingenuity, this could be expanded to become a very useful tool.

    Update: I’ve just seen that Daniel Glazman came up with a very similar proposition before I did: CSS-only tabs.

    Source:http://www.css3.info

    No comments:

    Post a Comment