Contextual Selector

From CSS Discuss

Jump to: navigation, search

Contextual Selectors can:

  • slimline your CSS and HTML a little
  • make it easier to see what is going on


Let's suppose you have a site masthead. This contains the site title (an H1) and some sort of tagline in a P.

Your masthead is probably a div, div.masthead or #masthead to position it and style it (see Classes Vs Ids). But what about the H1 and the P? Well, you've probably reserved H1 for just the site title (and started headers in the text at H2), but it's best to select it more specifically just in case future maintainers aren't so smart ;-)

You could give them masthead class:


This involves giving them a class in the HTML; plus you now have duplication of the "masthead" keyword. You might want to use "mastheadbox" for the div, say, but now you have two keywords floating around, which, from your point of view mean the same thing: things to do with the masthead.

Or, you could use contextual selectors:

#masthead h1
#masthead p

Your HTML is now simpler: there's only one element which has a CSS name. It's also clear from the CSS what the document structure is: the selectors mean: "the H1 and the P that are within the masthead".

The usage of contextual selectors you can see in the example:

 <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
 <title>Contextual selectors</title>
 <style type="text/css">
  P B { 
   font-family: Times, serif; /* Font family */
   font-weight: bold; /* heavy faced type*/
   color: navy; /* blue colour of the text */
  < div>< b>heavy faced type</b ></div>
  < p>< b>The heavy faced type of the text and text highlighting takes part simultaneously</b></p>
In this example we see the common use of the tag < B> and its use, when it is put into paragraph

. The colour of the text and font are changed. Note It is not obligatory that context selectors consist of only one embedded tag. Depending on the situation it is supposed to apply one and more than one tags, logically embedded into each other

Personal tools