[CSS] Selectors (1) – Basic Selectors

As a web developer, CSS is one of the basic skills, which anyone needs to master. Selectors are the most important feature of CSS. Moreover, by learning CSS selectors you can also learn the big part of jQuery.  Let’s start from the easy ones.


1. Basic CSS Selectors

There are 4 Basic CSS selectors (tag, class, id, and universal) and 2 basic+ selectors (class-dependent and id-dependent).

  • HTML element selector: tagname
  • Class selector: .classname
  • ID Selector: #idname
  • Universal Selector: *
  • Dependent class selctor: tagname.classname
  • Dependent id selector: tagname#idname


2. Example

We have a following html document.

<h1>Today's tasks</h1>
<p id="task1" class="high">Meeting at 9am</p>
<p id="task2" class="medium">Tech Support</p>
<p id="task3" class="high">Meeting at 11am</p>
<p id="task4" class="low">Lunch</p>

	<li id="task5">Meeting at 2pm</li>
	<li id="task6">Tea Time at 3pm</li>
  • HTML tag selector: “h1”, “p”, “li”
  • Class selector: “.low”, “.medium”, “.high”
  • ID Selector: “#task1”, “#task2” …
  • Universal Selector: *
  • Dependent class selctor: “p.high”, “li.high” …
  • Dependent id selector: “p#task4”, “li#task5” …

Easy and straightforward.

Just remember. Class selectors use a dot “.” and ID selectors use a sharp “#“.


3. Style Precedence – Specificity

Specificity describes the weight of a selector.

  • Universal Selector “*” :   (0,0,0,0)
  • Element Selector : (0,0,0,1)
  • Class Selector “.” : (0,0,1,0)
  • ID Selector “#” : (0,1,0,0)
  • Inline style: (1,0,0,0)

Let’s look at the following example.

  <style type="text/css">
    #greetMsg { font-size: 2em; }
    .hello { font-size: 1.2em; }
    * { font-size: 1em; }
    div { font-size: 0.7em; }
  <div id="greetMsg" class="hello">Hello, World</div>

The ID selector “#greetMsg” will be used because it has the higher weight than others.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s