Pages

Labels

Powered by Blogger.
Thursday, August 30, 2012

Common selectors


The most common kinds of selectors are type and descendant selectors. Type selectors are used to target a particular type of element, such as a paragraph or a heading element. You do this by simply specifying the name of the element you wish to style. Type selectors are sometimes also referred to as element or simple selectors.



p {color: black;}
h1 {font-weight: bold;}

Descendant selectors allow you to target the descendants of a particular element or group of elements. A descendant selector is indicated by  a space between two other selectors. In this example, only paragraph elements that are descendants of a blockquote will be indented, while all other paragraphs will remain unchanged.

blockquote p {padding-left: 2em;}

These two types of selector are great for applying generic styles that apply across the board. To be more specific and target selected elements, you can use ID and class selectors. As the names suggest, these selectors will target elements  with the corresponding ID or class name. ID selectors are identified using a hash character; class selectors are identified with a period. The first rule in this example will make the text in the introductory paragraph bold, and the second rule will make the date grey:

#intro {font-weight: bold;}
.date-posted {color: #ccc;}

<p id="intro">Happy Birthday Andy</p>
<p class="date-posted">24/3/2009</p>


As I mentioned previously, many CSS authors develop an overreliance on class and ID selectors. If they want to style headlines one way in  the main content area and another way in the secondary content area, there is the tendency to create two classes and apply a class to each headline. A much simpler approach is to use a combination of type, descendant, ID, and/or class selectors:

#main-content h2 {font-size: 1.8em;}
#secondaryContent h2 {font-size: 1.2em;}

<div id="main-content">
  <h2>Articles</h2>
    ...
</div>
<div id="secondary-content">
  <h2>Latest news</h2>
    ...
</div>

This is a very simple and obvious example. However, you will be surprised how many elements you can successfully target using just the four  selectors discussed so far. If you find yourself adding lots of extraneous classes to your document, it is probably a warning sign that your document is not well structured. Instead, think about how these elements differ from each other. Often, you will find that the only difference is where they appear on the page. Rather than give these elements different classes, think about applying a class or an ID to one of their ancestors, and then targeting them using a descendant selector.

0 Comments: