Last Updated: September 09, 2019
·
4.001K
· elad2412

CSS Target Event

In CSS3 we were first introduced with a new feature called target pseudo class which makes CSS behavior more & more similar to JavaScript events.

target event

target pseudo class event occurs when the click event takes place on an Anchor that has another element id on its href attribute.

How it's done:

  1. First of all we'll add a div.container with some images inside, for every image we'll set an ID attribute.

    <div class="container">
      <img id="item1" src="images/item1.jpg" />
      <img id="item2" src="images/item1.jpg" />
    </div>
  2. After we set the images ids, we can add anchors that every one of them points through its href to a single image by its ID.

    <a href="#item1" class="button">image 1</a>
    <a href="#item2" class="button">image 2</a>
  3. Lets write some CSS:

    /* set size to our container */
    .container{
      width:200px; 
      height:200px; 
      background-color:#ddd;
      margin-bottom:10px;
    }
    /* hide images & set image size*/
    .container img {display:none; width:200px;}
    
    /*set link to look like buttons*/
    .button{
      font-weight:bold;
      text-transform:uppercase;
      display:inline-block;
      margin-right:10px;
      color:white;
      display:ibline-block;
      background-color:#5562c1;
      padding:10px;
      border:solid 2px #333;
      border-radius:10px;
      text-decoration:none;
      margin-bottom:10px;
    }
    .button:hover{background-color:#3f498e;}
  4. Now the most important part is to add target styles (:target), which on click event will display the selected target image.

    .container img:target{display:block;}

Picture

Full Live Example

  • with target styles you can make even more cool stuff. A small POC example I made, a image gallery without javascript at all!

POC - CSS Gallery Live Example

Another nice example from the web

Enjoy!

If you like this tip, I will be happy to get your LIKE. You are welcome to follow me and endorse my skills.

Elad Shechter