Some less commonly-used CSS selectors
February 11, 2009
Web Building

We all know the common CSS selectors that most of us use every day:
Select by Classname:
.classname {color:#000}

Select by Element ID:
#id {color:#000}

Select by tagname:
tagname {color:#000}

And combinations of these:

Select all elements within Element ID "myid" with classname "myclassname":
#myid.myclassname {color:#000}

Select all elements with tag "mysecondtag" that are descendants of any element of type "mycontainertag"
mycontainertag mysecondtag {color:#000}


Here are some selectors that you may not know so well.

Child elements
Select all elements with tag "mysecondtag" that are descendants of any element of type "mycontainertag"
mycontainerTag>mysecondtag {color:#000}

The First-child element
Select the first child element with tag "mysecondtag" of any element of type "mycontainertag"
mycontainertag:first-child {color:#000}

What's the difference between a descendant and a child?
A descendant is any element that is contained within the parent element, no matter how far down the DOM tree. So child elements, grandchildren, great-grandchildren, etc. are all descendants. A child element is on the first level of the DOM tree within the parent. The first-child element is the FIRST element on the first level. So if you have a DIV with multiple P's inside it, the first P would be the first-child. If inside each P is an A element, then the A's are descendants of the DIV.

Note: IE 6 may not comprehend all combinations of child and first-child patterns.


Similarly, most of us know of the dynamic pseudo-classes A:link, A:visited, A: hover, and A:active, but did you know about A:focus? A:focus can be used to highlight the currently selected element on the page. See this page for a description of using the outline property to highlight focused elements

Adjacent elements
Select the element with tag "mytag" that immediately precedes any element with tag "myothertag"
mytag + myothertag

For a detailed explanation of all of these selectors see CSS2 Specification: Selectors

Ads by Google

Posted by ellen at February 11, 2009 09:43 AM


Ads by Google

 RSS   |   Contact Me

Ads by Google

Ads by Google