CSS Selectors

CSS Selectors allows you to select and manipulate HTML elements through the id, class, attribute and so on.

This the chapter will take you through the first knowledge of CSS selectors. Our tutorials are carefully arranged in the order of proper learning, which means there are later chapters on this tutorial that teaches more on CSS selectors. However if you want to jump into these chapters now, see them below, otherwise, let's move on.

The * (all) Selector

The all (*) Selector selects all the elements in an HTML document, including the <html> element.

To select all the elements in a webpage, use * sign.

*
{
display:none;
}
/* This example hides all element on the web page include the <body> */

  Do It Yourself

The Tag Selector

The tag selector selects elements based on their tag name.

The example below selects all the <h1> elements in the document.

h1
{
background : orange;
width : 100%;
}
/* This example changes the background color of every <h1> elements to orange*/

  Do It Yourself

The id Selector

An id (#) selector uses the id attribute of an HTML element to select a particular element.

To select an element with a specific id, write a preceding hash character(#), followed by the id of the element.

Syntax

#ID_name
{
  font-style: italic;
}

An id should be unique within a page, so that the id (#) selector is used if you want to select a single, unique element.

The CSS style below will be applied to the HTML element with id="test":

Example

#link
{ 
color : red;
text-decoration: underline; 
}
/* This selects an element with id="link" and applies the above definitions */

  Do It Yourself

The class Selector

The class selector selects all elements with a declared class attribute.

To select elements with a particular class, write a period character (.), followed by the name of the class: The CSS code below will select all HTML elements with class="underline" and will make them underlined.

Example

.underline
{
text-align: center;
color: red;
}

  Do It Yourself

Grouping Selectors

If you have elements with the same style definitions, for example:

a {
color: blue;
font-weight: bold;
} 
p {
color: blue;
font-weight: bold;
} 
span {
color: blue;
font-weight: bold;
}

To minimize these codes, you can group them in one form, by separating each element with a comma (,).

In the example below we have group the selectors from the above example:

Example

a, p, span {
color: blue;
font-weight: bold;
}
Can you see the importance of categorizing selectors? - It saves a lot of work!

  Do It Yourself

What You Should Know at the End of This Lesson

  • You should be able to understand what CSS Selectors are.
  • You should be able to define a CSS property for specific elements, id names, and class names.
  • You should be able to make use of selectors categorization when you have the same style definitions for them.