css // css3 // code // html5

CSS3 Target Trick

In my previous post regarding a CSS Hover Trick, I was challenged in the twitter universe to do something similar with images, but with the click event.  Could this be done without JavaScript?  But of course.  What makes this possible is use of two CSS3 selectors:not, :target. This will not work in older browsers, so check out how to do feature detection in this post on detecting CSS3 selectors.

The code found below will make images appear based on what anchor tag was clicked without using  any JavaScript!  Here are screen captures to demonstrate the desired behaviors:

No anchor tags have been clicked


First anchor tag clicked


Second anchor tag clicked


Third anchor tag clicked
Shameless self promotion


Here is the code to make it all work!  To reproduce in your own environment, simply replace the images with your own!

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>CSS Target</title>
        #csstarget ul { 
            margin:             0;
            padding:            0; 
        #csstarget li {
            list-style-type:    none;
            display:            inline;
            margin-right:       2em;  
        img {
            width:              8em;
            height:             8em;
        #images {
            padding:            3em;
        /* hide unselected targets */
        #images img:not(:target) {
            display:            none;
        /* display selected target */
        :target {
            display:            inherit;
    <article id="csstarget">
        <h1>CSS Target Trick</h1>
        <p>Click on any word to reveal an image...</p>
            <li><a href="#img01">CSS3</a></li>
            <li><a href="#img02">HTML5</a></li>
            <li><a href="#img03">Palermo4</a></li>
        <div id="images">  
            <img id="img01" src="images/css3logo.png" />
            <img id="img02" src="images/html5.png" />
            <img id="img03" src="images/palermo4_bw.png" />

    Copyright © Microsoft Corporation. All rights reserved.
    The code provided in this post is licensed under the Microsoft Public License (Ms-PL).
blog comments powered by Disqus