
1 2 3 4 |
a{ color:blue; background:red; } |
ID Selector: In an HTML tag when you use an ID of an element as: <h1 id=”some_id” >Some Heading</h1> You are not just doing that for javascript uses, you can use it for design purposes as well:
1 2 3 |
#some_id{ margin-left:20px; } |

Class Selector: Now what to do when you wanna apply the same styles to a set of elements. Well, that is when the class attribute of the HTML tags comes into play. Suppose there are two tags as such:
1 2 3 4 5 6 7 8 |
<h1 class="yo">Some Cool heading</h1> <a href="#" class="yo" >Some Link</a> <style> .yo{ color:white; background:orange; } </style> |
Descendant Selector: Most of the times the HTML Documents have a lot of tags, nested inside other tags and we obviously cannot give a class/id to every other element. CSS comes to the rescue again by providing us with the descendant selector. Consider this piece of code:
1 2 3 4 5 6 7 8 9 |
<div> <p>Some paragraph here(inside the div tag)!</p> </div> <p>Another paragraph (not inside the div tag).</p> <style> div p{ background:yellow; } </style> |
DEMO
Some paragraph here(inside the div tag)!
Another paragraph (not inside the div tag).
1 2 3 4 5 6 7 8 9 10 11 12 |
<div> <p>Some paragraph here(inside the div tag)!</p> </div> <p>Another paragraph (not inside the div tag).</p> <style> p{ background:red; } div p{ background:yellow; } </style> |
DEMO
Some paragraph here(inside the div tag)!
Another paragraph (not inside the div tag).

The Direct Descendant Selector: This one is just like the descendant selector except that it only matches an element which is nested to just one level of the parent element.For example:
1 2 3 4 5 6 7 8 9 |
<div class="test"> <p>Nested level 1</p> <div><p>Nested level 2</p></div> </div> <style> .test > p{ color:red; } </style> |
DEMO
Nested level 1
Nested level 2
Combination of Selectors: A great thing about CSS is you can make even match elements with some custom combination based on any valid CSS selectors. For example:
1 2 3 |
div#abc{} /*This will match the div with id abc*/ div .some_class{} /*This will match all the elements having class=<strong>some_class</strong> that are a descendant of a div element*/ #abc div > p a{} /*Figure it out yourself :P */ |
Hope, I helped you a little to understand how the basic selectors work in CSS. There are a lot more advanced and useful selectors that one can use in his projects. But we will get there in a little time. Until then, keep sharing learning and practicing!
Follow Us