18/07/2016

CSS Selectors

CSS selectors indicates the HTML element on which a style will be applied based on their id, class, type, attribute and more.

Selector Types


  • Element Selectors - are global in nature. They affect each and every element of that type.
  • Class Selector - working with HTML class attributes. A class attribute name can be anything can be used as many elements as possible.
  • Descendent Selectors - allows target an element based on where it's found. To do so, simply string the selectors together, separating them with whitespace. The parent selectors are added first, followed by each successive nested selector.

Element Selector


Element selector select elements based on the element name like < h1 >, < table > etc.

h1 { color: blue; }

The above statement will the change the color of all h1 elements color to blue in a webpage. 

id Selector


CSS allows to change the style using the id attribute of an HTML element.

To select an element with a specific id, there is a need to use hash ( # ) character before the id name.

#content-wrap 
{
 text-align: left;
 color: #333333;
}


The above example will change the style of only HTML element which has content-wrap as the id attribute in a webpage.

The class Selector


CSS allows to change the style using the specific class attribute of an HTML element.

To select an element with a specific class, there is a need to use period ( . ) character before the class name.

.left 
{
 text-align: left;
 color: #333333;
}


The above example will change the style of only HTML element which has content-wrap as the class attribute in a webpage.

It is also possible to specify the only specific HTML elements should be affected by a class. like below:

h1.left 
{
 text-align: left;
 color: blue;
}


Grouping Selectors


In CSS it is possible to apply a style to many selectors if required. To do so, just separate the selectors with a comma.

h1 
{
 text-align: left;
 color: blue;
}

h2 
{
 text-align: left;
 color: blue;
}

h3 
{
 text-align: left;
 color: blue;
}


Instead of initializing the same style to different element as in above example, we can follow the below example - 


h1, h2, h3 
{
 text-align: left;
 color: blue;
}