Thursday, December 12, 2013

The CSS3 :target pseudo-class

Some years ago, in 2005, I attended a workshop about CSS. Andy clark told us about the near future and showed us an example of a completely CSS driven web page. We all thought that there was some kind of javascript there but Andy said that the secret was the CSS3 :target pseudo-class.

You can run this jsFiddle http://jsfiddle.net/jurquizu/Wtr4g/ for a live example.

The idea behind the :target pseudoclass is that the target element of an anchor can have its CSS rules. For example the anchor link "#info" is targetting the paragraph with id "info". When we click this link, the CSS selector p#info:target is triggered and all its rules are applied.

HTML

  1. <p>Click on the link to show the hidden paragraph: <a href="#info">show me</a>.</p>  
  2. <p id="info">This is the hidden paragraph.</p>  

CSS

  1. /* here's pseudoclass-target in action */  
  2.   
  3. p#info {  
  4.     display:none;  
  5. }  
  6.   
  7. p#info:target {  
  8.     display:block;  
  9.     border:2px solid red;  
  10.     background-color:yellow;  
  11.     width:250px;  
  12.     text-align:center;  
  13. }  

No comments: