03. Basic Selectors

Selectors give you the power to pick and choose which elements to style. There are nearly 30 different selectors to use - that's a lot of power! Remember that CSS selectors are case sensitive, so they must match the names and values exactly.

Let's start with some of the most basic selectors.

Type (or Element) selectors

Type selectors specify HTML tags that you can grab right from an HTML document. Simply choose the name of the HTML tag to change its style.

h1 {
  color: red;
}

This selects all text within <h1> tags and sets the font color to red.

To apply multiple type selectors in one go, we can group the elements together with a comma.

h2, p {
  color: blue;
}

This would take all text within <h2> and <p> tags and set its color to blue. This is also known as grouping.

Class selectors

Within the HTML tag, we can specify a class selector with the class HTML attribute.

<span class="intro">This is my introduction.</span>

The value is whatever you'd like to name that class. Inside your CSS style sheet, select the class by preceding its name with a period (.). To target all class attribute with value of "intro":

.intro {
  text-decoration: underline; 
}

We can be more specific and combine tag and class selectors, giving more specificity. To target only <p> elements with class "intro":

p.intro {
  color: red;
}

This will take elements such as:

<p class="intro">I'm selected!</p>

ID selectors

You may also specify an id instead of a class. The only difference is that multiple elements can share the same class, but only one element can have a specified ID. This means that you will only be specifying a single element with an ID selector.

<p id="subheading">I'm selected!</p>

To select an element based on its ID, precede its name with a hash (#). For example, to target an element with the ID "outro":

#outro {
  font-weight: bold;
}

Universal Selectors

Universal selectors are used to target every element. This is denoted by the asterik (*). To select all elements on the document,

* {
  color: red;
}

Build modern and responsive webpages

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Ad