Site icon Sir Codex

How to Put Your CSS3 on :target

CSS pseudo-classes which change styles in response to user actions have been with us for many years. You’ve almost certainly used :hover, :active and :focus; I can (only just) remember the excitement of changing IE4’s link colors back in 1997.

CSS3 also introduced :target; a powerful pseudo-class which can reduce the need for scripting in interactive widgets. Consider a page URL such as http://mysite.com/page#mytarget; an element with the id “mytarget” can have matching :target styles applied.

:target Browser Support

All modern browsers support :target and you won’t experience problems with IE9 or most versions of Chrome, Firefox, Safari and Opera. Unfortunately, that still leaves us with the older versions of IE. I wouldn’t worry too much about IE6 and 7, but IE8 remains the world’s most used browser version. All is not lost, however, since shims such as selectivizr can add :target support without requiring complex workarounds.

A Simple Document :target

We’ve recently been discussing website contracts. Generic contract small print such as payment schedules, hosting conditions, cancellation terms, support policies, glossaries etc. could be contained in one or more web pages. The document could grow to a considerable length even if you try and keep it concise!

Let’s look at a snippet of the document’s HTML5 in contract.html:


<h1>Website Contract</h1>

<nav>
	<ul>
		<li><a href="#payment">Payment Schedule</a></li>
		<li><a href="#support">Support &amp; Maintenance</a></li>
		<li><a href="#hosting">Hosting Terms</a></li>
		<li><a href="#glossary">Glossary</a></li>
	</ul>
</nav>

<article id="payment">
<h2>Payment Schedule</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</article>

<article id="support">
<h2>Support &amp; Maintenance</h2>
<p>Ut euismod tempor porttitor.</p>
</article>

<article id="hosting">
<h2>Hosting Terms</h2>
<p>Suspendisse ac nisl lorem, ut fermentum erat.</p>
</article>

<article id="glossary">
<h2>Glossary</h2>
<p>Aenean id nibh eget nisl blandit hendrerit lobortis ac tortor.</p>
</article>

We can use the :target attribute to highlight active sections, e.g.


article:target
{
	background-color: #ffc;
	border: 2px solid #fcc;
}

Anyone viewing the contract can click a navigation menu item to highlight the appropriate section. You can also issue direct links to clients who require specific information, e.g. contract.html#support.

The :target selector offers further versatility — it’s possible to create dynamic effects in HTML5 and CSS without using JavaScript.

 

Source Link: http://www.sitepoint.com/css3-target-selector/

Exit mobile version