All About Selectors

Selectors are what you use to target specific HTML elements to style. There are three types of selectors:

Tag An HTML tag such as h1 or p.
Class A class attribute of one or more elements, such as:

<p class="class-name">Sample text.</p>.

Referenced in CSS with a “.” before it.

ID An id attribute of a unique element, should only be used once, such as:

<section id="first">Sample header.</section>.

Referenced in CSS with a “#” before it.

The above table is from CSS Basics.

Selectors illustrated

Types of selectors: HTML tag, class, and id, and how they're used in HTML.

Types of selectors: HTML tag, class, and id, and how they’re used in HTML.

Remember this…

When you’re first learning CSS, here are the most important things to remember about selectors:

  • ID selectors use a “#” and may only be used for one element.
  • Class selectors use a “.” and can be used for more than one element. Classes are used for styles that repeat throughout the theme.

A quick exercise follows, if you want to dive deeper…

Exercise

Which one of these code samples uses id and class selectors correctly?

Sample #1


<h1 id="main-heading">Grocery List</h1>


<ul class="red-text">
    
<li>Onions</li>


<li>Radishes</li>

</ul>


<h1 id="main-heading">Garden List</h1>


<ul class="red-text">
     
<li>Herbs</li>


<li>Cacti</li>

</ul>

Sample #2


<h1 id="grocery-heading">Grocery List</h1>


<ul class="red-text">
    
<li>Onions</li>


<li>Radishes</li>

</ul>


<h1 id="garden-heading">Garden List</h1>


<ul class="red-text">
     
<li>Herbs</li>


<li>Cacti</li>

</ul>

Answer: Sample #2 is correct, because id selectors may only be used for one element. Sample 1 is incorrect because the two “h1” tags are using the same id selector of “main-heading”. If you wanted to use “main-heading” twice, it could be turned into a class selector instead.