Become Confident With CSS Selectors

Hello, everybody! 🚀 Today we’ll be covering CSS selectors in depth.

Become Confident With CSS Selectors

What does a CSS selector do?

What does a CSS selector do? To choose the HTML components that we wish to style, we utilise a pattern called a CSS selector.

Technically speaking, CSS selectors can choose which HTML components will receive a style ruleset.

Types of selectors

1. Universal selector

Syntax: * { style properties }

This selector, denoted by an asterisk (), matches *all of the HTML document's elements.

<ul>
  <li>Computer Science Eng.</li>
  <li>Mathematics</li>
  <li>Physics</li>
</ul>
* {
  border: 1px solid coral;
}

The behaviour of this selector is very clearly demonstrated by the border property. Every element, including the "body" and "html" elements, is now enclosed by a border, as seen in the image above.

To clear up misunderstandings and make your code simpler to comprehend, you may also utilise the universal selector.

2. Type selector

Syntax: elemType { style properties }

All elements that fit the specified type are found by this selector.

<p>A paragraph</p>
<p>Another paragraph</p>
<p>One more paragraph</p>

p {
  font-size: 1.5rem;
  color: deeppink;
}

This will apply a font size of 1.5rem and deep pink color to all <p> elements. Easy and direct.

3. Class selector

Syntax: .classname { style properties }

All elements that contain the specified class are matched by this selector, which is symbolised by a period (.).

This is a deep pink paragraph

This is a hot pink paragraph

This is a regular pink paragraph

This is a paragraph with a deep pink background

This is a paragraph with a hot pink background

This is a paragraph with a regular pink background

.deeppink {
  color: deeppink;
}
.hotpink {
  color: hotpink;
}
.pink {
  color: pink;
}
.deeppink-bg {
  background-color: deeppink;
}
.hotpink-bg {
  background-color: hotpink;
}
.pink-bg {
  background-color: pink;
}

/* Group selector - Stay until the end to understand its
 behavior 😉 */
.deeppink-bg, .hotpink-bg, .pink-bg {
  color: white;
}

This will apply a different pink color variant to every <p> element depending on the class they contain, styling either their text or their background.

4. ID selector

Syntax: #idname { style properties }

The hash symbol (#) used to symbolise this selector indicates that it matches the specific id-containing unique element.

<div>
  <table id="users-table">
    <th>Users</th>
    <tr>
      <td>John Doe</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
    </tr>
  </table>
  <table id="staff-table">
    <th>Staff</th>
    <tr>
      <td>Hannah Legend</td>
    </tr>
    <tr>
      <td>Daniel Oaks</td>
    </tr>
  </table>
</div>

/* Type selector */
table {
  padding: 20px;
}
/* ID selectors */
#users-table {
  background-color: black;
  color: white;
}
#staff-table {
  border: 1px solid black;
}

This will apply a 1px solid black border to the table that matches the id staff-table and a black background and white text colour to the table that matches the id users-table. Depending on their kind, both of them receive padding of 20px.

Important: Even though HTML allows you to assign the same id value to several elements, you shouldn’t ever do it. If you need to apply the same style to a bunch of different elements, always use the class attribute. You’ll keep your code clean and will get rid of a possible confusion.

5. Attribute selector

The attribute selection is more complicated than the other selectors and has a number of syntaxes that can be used with our HTML components depending on which condition needs to be met.

In other words, it matches all HTML elements that have a particular attribute and whose value meets a predetermined requirement.

Attribute selector syntaxes

Syntax 1

[attr] { style properties }

Matches elements with the specified attribute.

<nav>
  <ul>
    <li><a href="/">Home</a></li>
    <li><a href="/blog">Blog</a></li>
    <li><a href="/contact">Contact</a></li>
    <li><a href="/about">About</a></li>
  </ul>
</nav>

/* Type selector */
nav {
  background-color: darkslategray;
  padding: 10px;
}

/* Attribute selector */
a[href] {
  color: white;
  text-decoration: none;
}

> This will apply white color to every <a> the element that contains the href attribute, regardless of its value, and removes the underline.

We’re also styling the <nav> element with a background color and some padding by making use of the type selector.

Syntax 2

[attr=value] { style properties }

Matches elements whose value for attr is the exact value.

<form>
  <label for="username">Username</label>
  <input id="username" type="text" placeholder="Username" />
  <label for="password">Password</label>
  <input id="password" type="password" placeholder="Password" />
</form>

input[type="text"] {
  color: chocolate;
}

This will apply a chocolate text color to every <input> element that has the type attribute with an exact value of the text.

Group selector

Syntax: elem1, …, elemN { style properties }

This selector is represented by a comma (,) and matches all the elements stated in the list, and applies the same ruleset to all of them.

<h1>Computer Science Engineering</h1>
<h2>List of courses</h2>
<ul>
  <li>Algebra</li>
  <li>Calculus</li>
  <li>Physics</li>
  <li>Discrete Mathematics</li>
  <li>Introduction to Programming</li>
</ul>

h1, h2, li {
  color: darkred;
}

This will apply a dark red color to every <h1>, <h2> and <li> element.

Combining selectors

CSS selectors can also be combined. By combining selectors, then we can define CSS combinators.

CSS combinators are used to establish a relationship between different selectors and are very useful to make your element selection more targeted.

1. Descendant combinator

Syntax: elem1 elem2 { style properties }

This combinator is represented by a single space ( ) and matches all elem2 that are descendants of elem1.

Consider the following navigation:

<nav>
  <ul>
    <li><a>Home</a></li>
    <li>
      <a>People</a>
      <ul>
        <li><a>Students</a></li>
        <li>
          <a>Faculty members</a>
          <ul>
            <a>Discrete Mathematics</a>
            <a>Programming</a>
            <a>Physics</a>
            <a>Algorithms</a>
          </ul>
        </li>
        <li><a>Staff members</a></li>
      </ul>
    </li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
  </ul>
</nav>

nav a {
  border: 1px solid crimson;
  color: darkslateblue;
  font-size: 1.5rem;
  font-weight: bold;
}

This will apply a 1px solid crimson border, a dark slate blue color, a font size of 1.5rem, and a bold font-weight to every <a> an element that is descendant of a <nav> element, regardless of how nested they are.

2. Child combinator

Syntax: elem1 > elem2 { style properties }

This combinator is represented by a prompt (>) and matches all elem2 that are direct children of elem1.

<div class="box">
  <p>This is a direct child of .box</p>
  <div>
    <p>This is not a direct child of .box</p>
  </div>
  <p>This is another direct child of .box</p>
</div>

.box > p {
  color: darkgoldenrod;
}

This will apply a dark golden color to every <p> element that is a direct child of any element that has the class box, so, in this HTML example, the first and last <p> elements will be selected, but not the one in the middle.

3. General sibling combinator

Syntax: elem1 ~ elem2 { style properties }

This combinator is represented by a tilde (~) and matches all elem2 that are siblings to elem1 and come after it.

<img src="blue-mug.jpeg" alt="a regular blue coffee mug" />
<p>Blue mug</p>
<p>Price: $15</p>

img ~ p {
  color: darkblue;
}

4. Adjacent sibling combinator Syntax: elem1 + elem2 { style properties }

This combinator is represented by a plus symbol (+) and matches all elem2 that are siblings to elem1 and appears immediately after it.

<img src="blue-mug.jpeg" alt="a regular blue coffee mug" />
<p>Blue mug</p>
<p>Price: $15</p>

img + p {
  color: darkblue;
}

In this case, only the first <p> the element will be selected since the second one doesn't appear immediately after the <img> element.

Pseudo-classes

A CSS pseudo-class is a keyword that is added to a selector and defines a special state of the selected elements.

Syntax: Elem:pseudo-class { style properties }

This selector is represented by a colon (:).

<h1>Shopping list</h1>
<ul>
  <li>Milk</li>
  <li>Butter</li>
  <li>Eggs</li>
  <li>Sugar</li>
</ul>

li:hover {
  background-color: black;
  color: white;
}

In this example, we’re applying black background color and white text color to every <li> element when the cursor hovers over it.

Some of the most common CSS pseudo-classes are:

:active, :hover, :focus, :disabled, :checked, :first-child, :nth-child, :first-of-type.

Pseudo-elements

A CSS pseudo-element is a keyword that is added to a selector to style a specific part of the selected elements.

Syntax: elem:pseudo-element { style properties }

This selector is represented by a double colon (::).

<p>CODE</p>

p::before{
  content: "_";
}

Some of the most common CSS pseudo-elements are:

::after (can also be written as :after), ::before (can also be written as :before), ::marker, ::placeholder, ::first-letter.

And that's basically it.

I sincerely hope you've found this reference manual useful.

Â