Tuesday, March 2, 2010

CSS Selectors: The Basics

This post will demonstrate ways to use 'CSS Selectors' (http://www.w3.org/TR/CSS2/selector.html) to target parts of a webpage that you wish to track.

There are three basic ways of identifying parts of a webpage using css selectors:

1. Element 'Tag'
2. Element 'ID'
3. Element 'Class'

Let's give a quick practical example of each of three ways of identifying content:

1. 'Tag' - a tag is the name given to the type of structural element. For example in a typical webpage 'normal' text is often placed with 'paragraph' tags like this:

<p>This is the first paragraph</p>
<p>This is the second paragraph</p>

If we wanted to select all of the paragraphs in a webpage, our 'CSS Selector' would simply be p.

?? other examples of tag selection
<h1>foo</h1>

2. 'ID' - Every structural tag in a webpage can have defined an optional 'id' attribute. Within a single webpage no two elements should have the same 'id'. Therefore an 'id' should point directly to a single element somewhere in the page.  For example

<p>here is a paragraph of text<p>
<p id="error-message">This is an error message!</p>

If we just want to extract the error message our selector would simply be #error-message. The '#' symbol is important and tells Femtoo that we are looking for an id.

3. 'Class' - Every webpage tag can contain a 'class'. Actually, they can contain as many classes as you want. Here is an example of how classes might be used in a navigation menu in a webpage:

<ul id="menu">
<li class="menu-item"><a href="#">Products</a></li>
<li class="menu-item selected"><a href="#">Services</a></li>
<li class="menu-item"><a href="#">Contact Us</a></li>
</ul>

...well sort of... actually using .selected might not be specific enough - this means that we would end up selecting the content of every single element on the page that contains a 'selected' class. In our example, a better selector might be: .menu-item.selected - which means retrieve all elements that contain both the 'selected' class and the 'menu-item' class. Actually, we can be even more specific with #menu .menu-item.selected. By using the #menu selector we are ensuring that we will not accidentally select other items in the page that also have the classes 'menu-item' and 'selected'

2 comments:

  1. It's Best To Participate In A Contest For Top-of-the-line Blogs On The Web. I Will Advocate This Site! taruhan bola kita

    ReplyDelete
  2. You Made Some Decent Points There. I Did A Search On The Issue And Found Most People Will Approve With Your Site. agen betting terpercaya

    ReplyDelete