HTML and CSS Reference
In-Depth Information
Using Contextual Selectors to Show Location
In the header design for the fictional travel site, we've used a class of current to show the
location in the site. If this were a site that was manually maintained, it would soon be a pain to
update new pages. If it were programmatically generated, maintenance would be less of an
issue, but there's a cunning way you can manage this with CSS (and this technique is closely
related to the one demonstrated in Chapter 8 for changing a page layout by switching a body
id attribute).
First, you need to add a class to each of the header links. The class name should be obviously
related to the link destination, like so:
<div id="tablinks" class="clearfix">
<ul>
<li><a class="home" href="/">Home</a></li>
<li><a class="travel" href="/travel/">Travel</a></li>
<li><a class="flights" href="/flights/">Flights</a></li>
<li><a class="hotels" href="/hotels/">Hotels</a></li>
<li><a class="late-deals" href="/late-deals/">Late Deals</a></li>
</ul>
</div>
In the body you add a class attribute that matches the page you are currently on. Assuming
that it's a page in the travel section, you'd have
<body id="cols3" class="travel" >
Note You could use an id instead of a class , but we've already used that for the purpose of defining the
page layout.
Now what we need is some CSS that makes the connection between the class attribute in
the body and the class attribute in the links. And here's the very CSS required (which we can
apply to five contextual selectors in one go by comma-separating them):
body.home a.home,
body.travel a.travel,
body.flights a.flights,
body.hotels a.hotels,
body.late-deals a.late-deals {
background:#047070 url(tab-bg-hover.gif) repeat-x top;
}
Taking the first line, it translates to “If the body element has a class of home , set links with
a class of home with this background image.” Of course, you need to be sure that you don't
apply the class of home , travel , or whatever your terms are to just any link—reserve them for
the header, or whichever navigation mechanism you intend to apply this technique to.
Search WWH ::




Custom Search