css3 onClick using :target

David Jones
@david3jones
avatar-davidejones

If you haven’t come across the :target psuedo class yet you may have missed a trick, its a great piece of css that can give you a more active page without the need of javascript. The easiest way to imagine this working is to actually think of click events in javascript. Lets say you have a href link with an onClick event attached to it. Clicking this triggers some javascript to show a div somewhere in the page. To do this in javascript you might have some code like this

<a href="#" onClick="document.getElementById('box1').style.display='block'">Click Me</a>
<div id="box1" style="display:none;">test test</div>

Well this very same functionality is available using just the :target css and to great effect. Take this code below as an example, here we can do exactly the same as the javascript but now just with css.

<style type="text/css">
    	#box1 {
    		display:none;
    	}
    	#box1:target {
    		display:block;
    	}
</style>
    
<a href="#box1">Click Me</a>
<div id="box1">test test</div>

Of course there are the usual browser limitations but consider combining this with javascript as a fallback and you can have a more future proof native version of your code. Combine this with some of the css animation effects and you can have something that would easily fool others into thinking its made with javascript when in fact its css.

Comments

  • avatar-sm1
    # Sm1
    I’ve been looking everywhere for an answer for my question .. How can I show another div when clicking on another using only CSS ??
    • avatar-alex
      # Alex
      I don’t think you can yet or maybe ever since thats not how css is made…for now im using the jquery way but css-only would be great.
  • avatar-ramesh
    # Ramesh
    Try pseudo state :active. Make sure the element you are trying to show is descendan
  • avatar-ramesh
    # Ramesh
    This post of :target should accomplish
  • avatar-ali
    # Ali
    Very useful thanks.
  • avatar-aniket
    # aniket
    I want to use this code for my website. What is the code by which by clicking my visitors can see particular code which is hidden initially but seen after the click and they get redirected to a particular url. Pls help

Comments are currently closed