21 December 2016

Lecture 13: Element, Class and ID Selectors


A CSS rule is written like this:

selector {
   statement;
}

The selector decides on which HTML elements the CSS rule will be applied to. (Remember that we can have more than one statement in a CSS rule.)

There are three main types of selectors:
  1. Element selector
  2. Class selector
  3. ID selector
An element selector directly mentions the HTML element name on which the CSS rule is to be applied. 

Here is an example: (You need to click on the CSS tab to see the CSS code.)



The CSS rule has an element selector - h3. So the rule is applied to all (here two) h3 elements of the HTML. The text-align: center; statement causes the h3 elements to be centrally aligned. 


Next, suppose we have three h3 elements in a page but we only want to centrally align the first and the last one. In these cases we can use the class selector.

Here is an example:



You can see that the heading Paragraph 2 is not centrally aligned. Notice the HTML. We have added class attributes to the first and last h3 opening tags. We have named them
center. Actually we could have given any class name to them.

In the CSS we have used .center (notice the dot) as our selector. Now all HTML elements of the class center will have that CSS rule applied to them. Again, it doesn't matter what class name we give, we could have given the first and last h3s a class name xyz. And then .xyz CSS selector will centrally align them.

So, we use class selectors to select multiple HTML elements from a group of elements. 

The ID selector is used to select one particular HTML element. Though several HTML elements can have same class, one ID can't be used more than once.



In the example above, we have used both the ID and class selectors. Note that while creating CSS rule for ID, we use # before the ID name.

NOTE: There should be no gap between the dot . or hash # and the class or ID name.

An HTML element can have both a class and an ID. Note the CSS of this example carefully:



We can apply a CSS rule to multiple elements (i.e. selectors) by using commas. Example:

p, h1 {
   color: blue;
   text-align: center;
}

The above CSS rule will be applied to every p and h1 elements.

Another example:

div, .real {
   color: green;
   font-size: 30px;
}

This CSS rule will be applied to every div element and to every element of real class.