DEV Community

Cover image for Mastering CSS Selectors: A Comprehensive Guide
Shefali
Shefali

Posted on • Updated on • Originally published at shefali.dev

Mastering CSS Selectors: A Comprehensive Guide

Cascading Style Sheets (CSS) is a fundamental language used for styling web pages, to enhance its appearance. It not only enhances the appearance of web pages but also precisely targets and styles specific HTML elements.

And fear not, because I’m here to guide you through this journey of applying styles to your HTML elements specifically using CSS selectors.

Let’s start!

What are CSS Selectors?

CSS selectors are components of CSS that allow you to precisely target and apply styles to specific HTML elements on a web page. They determine which elements in the HTML document will be affected by the defined CSS rules.

Basically, selectors select the HTML element and apply the style to particularly that element.

Now let’s learn about the different types of CSS selectors.

Basic Selectors

We have the following types of selectors in basic selectors.

  • Element Selector

The element selector selects the elements based on their tag name.

For example, style the text color of all <h1> elements to red.

h1 {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Another example, align all <p> elements to the center.

p {
  text-align: center;
}
Enter fullscreen mode Exit fullscreen mode
  • Class Selector

The class selector selects the elements based on their class attribute. To select the elements with their class names use . just before the class name.

For example:

<h1 class="heading">This is a heading.</h1>
<p>This is a heading.</p>
<h2 class="heading">This is a also a heading.</h2>
Enter fullscreen mode Exit fullscreen mode

Now we will select all the elements with the class “heading”.

.heading{
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the text color of all elements having a “heading” class.

  • ID Selector

Since the id of an element is unique within a page, so the id selector selects a single element with a specific id attribute.

To select the element with its specific id use # character before the id name.

For example:

<h1 id="heading">This is a heading.</h1>
<p>This is a heading.</p>
Enter fullscreen mode Exit fullscreen mode

Now we will select the specific element with the id “heading”.

#heading{
  color: red;
}
Enter fullscreen mode Exit fullscreen mode
  • Universal Selector

The universal selector selects all the elements on the page. To select all the elements of the web page just use a * sign.

For example:

* {
  margin: 0;
  padding: 0;
}
Enter fullscreen mode Exit fullscreen mode

This will set the margin and padding of all the elements to 0.

Combinators

We have the following types of combinators.

  • Descendant Combinator

The Descendant Combinator selects elements that are descendants of a specified parent element.

But what are descendants?

Let me explain.

A descendant is simply an element that is inside another element. For example:

<div>
   <h1>This is a heading.</h1>
</div>
Enter fullscreen mode Exit fullscreen mode

Here, <h1> is a descendent of <div>.

Now let’s get back to the descendent combinator.

The Descendant Combinator selects elements that are descendants of a specified parent element. The key idea here is that you should not be concerned about how deeply nested the descendant elements are inside the parent. Whether they are directly inside the parent or several levels deep, you can target all of them.

To select the descendent write the tag name, class attribute or id attribute of the parent element and after a space write the name of the descendent.

For example:

<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
Enter fullscreen mode Exit fullscreen mode

CSS:

section p {
  font-size: 20px;
}
Enter fullscreen mode Exit fullscreen mode

This will change the font-size of all the <p> elements inside the <section> element, regardless of their level of nesting.

What if there’s another <p> element outside the <section> element?

<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
<p>This is a paragraph outside the section element.</p>
Enter fullscreen mode Exit fullscreen mode

Then the font-size: 20px; will not apply to the <p> outside of the <section> element.

A Descendant Combinator only selects the elements that are inside the parent element.

Select using class attribute:

<section class="header">
   <p>This is a paragraph.</p>
   <p>This is another paragraph.</p>
</section>
Enter fullscreen mode Exit fullscreen mode

CSS:

.header p {
  font-size: 20px;
}
Enter fullscreen mode Exit fullscreen mode

Select using id attribute:

<section id="header">
   <p>This is a paragraph.</p>
   <p>This is another paragraph.</p>
</section>
Enter fullscreen mode Exit fullscreen mode

CSS:

#header p {
  font-size: 20px;
}
Enter fullscreen mode Exit fullscreen mode
  • Child Combinator

The child combinator selects elements that are a direct child of a specified parent element.

To select the direct child element use the > sign between the parent and child element.

For example:

<ul>
  <li>HTML</li>
  <li>CSS</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

CSS:

ul > li {
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Let’s take another example.

<section>
    <p>This is a paragraph.</p>
    <div>
      <p>This is another paragraph.</p>
    </div>
</section>
Enter fullscreen mode Exit fullscreen mode

Now, we want to change the text color of the <p> element of <section> element.

section > p {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

Will it change the text color of <p> inside <div> element?

This will not.

Because we have used the > sign between <section> and <p>, so this style will only apply to the direct child <p> element of <section> element.

  • Adjacent Sibling Combinator

The adjacent sibling combinator selects an element that is immediately preceded by a specific sibling element.

To put it simply, an adjacent sibling combinator selects an element that is an immediate sibling of the specified element, and there should be no other elements in between them.

The adjacent sibling combinator is represented by ‘+’ sign.

For example:

<h1>This is first heading.</h1>
<h2>This is second heading.</h2>
<h2>This is another second heading.</h2>
Enter fullscreen mode Exit fullscreen mode

Now we want to change the text color of the first <h2> element, not all <h2> elements. Then we can use the adjacent sibling combinator.

h1 + h2{
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above style will only change the color of the <h2> element which is an immediate sibling of the <h1> element that means which comes just after the <h1> element and there should be no other element between them.

  • General Sibling Combinator

The general sibling combinator selects sibling elements that share the same parent element and come after the specified element. This combinator does not require the selected element to be immediately preceded by the specified element.

The general sibling combinator is represented by the ~ symbol.

For example:

<p>I'm sibling paragraph of div.</p>
<div>
   <p>This is a paragraph inside a div.</p>
   <p>This is another paragraph inside a div.</p>
</div>
<p>I'm sibling paragraph of div.</p>
<h6>I'm sibling heading of div.</h6>
<p>I'm sibling paragraph of div.</p>
Enter fullscreen mode Exit fullscreen mode

Now suppose we want to style all the sibling <p> elements of <div> element that comes after the <div> element.

div ~ p {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

The above style will not change the style of <p> element that is before the <div> element because the general sibling combinator selects sibling elements that come after the specified element and here specified element is <div> .

Pseudo-Class

A pseudo-class is used to define a special state of an element, which means style an element when a user moves the mouse over it or style an element when it gets focus etc.

Syntax for pseudo-class:

element:pseudo-class {
  property: value;
}
Enter fullscreen mode Exit fullscreen mode

Now let’s take a look at some of the pseudo-classes.

  • Interactive States

:hover

Selects an element when a user hovers their mouse pointer over it.

For example:

<button>Hover over me!</button>
Enter fullscreen mode Exit fullscreen mode

CSS:

button:hover {
  background-color: black;
  color: #fff;
}
Enter fullscreen mode Exit fullscreen mode

:active

Selects an element when a user clicks on it.

For example:

<a href="/">Click me!</a>
Enter fullscreen mode Exit fullscreen mode

CSS:

a:active {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

:focus

Select an element that is in a focus state.

 <input type="text">
Enter fullscreen mode Exit fullscreen mode

CSS:

input:focus {
  background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

:visited

Style links that have been visited.

<a href="/">Click me!</a>
Enter fullscreen mode Exit fullscreen mode

CSS:

a:visited {
  color: purple;
}
Enter fullscreen mode Exit fullscreen mode
  • Styling Form Elements

:disabled

You can style disabled inputs differently using :disabled pseudo-class.

<input type="text" disabled />
Enter fullscreen mode Exit fullscreen mode

CSS:

input:disabled {
  border-color: red;
}
Enter fullscreen mode Exit fullscreen mode

:enabled

You can style enabled inputs differently using :enabled pseudo-class.

 <input type="text" />
Enter fullscreen mode Exit fullscreen mode

CSS:

input:enabled {
  border-color: green;
}
Enter fullscreen mode Exit fullscreen mode

:checked

You can style the inputs after being checked using :checked pseudo-class.

<input type="checkbox" />
<input type="radio" />
Enter fullscreen mode Exit fullscreen mode

CSS:

input:checked {
  height: 30px;
  width: 30px;
}
Enter fullscreen mode Exit fullscreen mode
  • Styling Child Elements

:first-child and :last-child

You can style the first child element and last child element of a parent element using :first-child and :last-child pseudo-classes respectively.

For example:

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

CSS:

ul li:first-child{
  color: purple;
  font-size: 20px;
}
ul li:last-child{
  color: indigo;
  font-size: 30px;
}
Enter fullscreen mode Exit fullscreen mode

:nth-child()

:nth-child() allows the selection of specific child elements based on their positions.

For example:

 <div>
    <p>This is first paragraph.</p>
    <p>This is second paragraph.</p>
    <p>This is third paragraph.</p>
    <p>This is fourth paragraph.</p>
    <p>This is fifth paragraph.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

/* This will change the color of p at second position. */
div p:nth-child(2) {
  color: red;
}
/* This will change the color of p at fourth position. */
div p:nth-child(4) {
  color: green;
}
/* This will change the color of every p at odd number position. */
div p:nth-child(odd) {
  color: yellow;
}
/* This will change the color of every p at even number position. */
div p:nth-child(even) {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

You can try all the above styles one by one.

:nth-of-type()

:nth-of-type() narrows down the selection to a specific element type.

For example:

 <div>
    <p>This is first paragraph.</p>
    <p>This is second paragraph.</p>
    <p>This is third paragraph.</p>
    <p>This is fourth paragraph.</p>
    <p>This is fifth paragraph.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

/* This will change the color of p at multiple of 2 positions. For example: 2, 4, 6... */
div p:nth-of-type(2n) {
  color: red;
}
/* This will change the color of p at multiple of 5 position. For example: 5, 10, 15... */
div p:nth-of-type(5n) {
  color: green;
}
Enter fullscreen mode Exit fullscreen mode

:not()

:not() pseudo-class is used for excluding specific elements from being styled.

For example:

<div>
   <p>This is first paragraph.</p>
   <p>This is second paragraph.</p>
   <p class="third">This is third paragraph.</p>
   <p>This is fourth paragraph.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS:

div p:not(.third) {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the color of all <p> elements excluding the <p> element which has a class named third.

Pseudo-Elements

A pseudo-element is used to apply styles to specified parts of an element. For example, style the first letter, or first line of an element, and insert content before, or after, the content of an element.

Syntax:

element::pseudo-element {
  property: value;
}
Enter fullscreen mode Exit fullscreen mode
  • ::before

This is used to insert content before the selected element’s content.

<blockquote>This is a quote.</blockquote>
Enter fullscreen mode Exit fullscreen mode

You can insert the " sign before the text using :before.

blockquote::before {
  content: '"';
}
Enter fullscreen mode Exit fullscreen mode
  • ::after

This is used to insert content after the selected element’s content.

<blockquote>This is a quote.</blockquote>
Enter fullscreen mode Exit fullscreen mode

You can insert the " sign after the text using :after.

blockquote::after {
  content: '"';
}
Enter fullscreen mode Exit fullscreen mode
  • ::first-line

This is used to change the style of the first line of the text.

<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

p::first-line{
  color: red;
}
Enter fullscreen mode Exit fullscreen mode
  • ::first-letter

This is used to change the style of the first letter of the text.

<p>This is a paragraph.</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

p::first-letter{
  color: red;
}
Enter fullscreen mode Exit fullscreen mode
  • ::marker

This is used to change the style of the marker of the list item.

<ul>
  <li>HTML</li>
  <li>CSS</li>
  <li>JavaScript</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

CSS:

::marker {
  color: green;
}
Enter fullscreen mode Exit fullscreen mode
  • ::selection

This is used to change the style of the selected text.

<p>
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis, dolorum
  similique, aliquid repellat beatae vero aliquam quis magnam, laboriosam
  cum eligendi quo harum reiciendis at fugit soluta quos nisi suscipit!
</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

::selection {
  color: white;
  background-color: purple;
}
Enter fullscreen mode Exit fullscreen mode

Attribute Selectors

Attributes of HTML elements provide additional information about the HTML element. You can style the elements by targeting them using their attributes.

  • [attr]

Selects the elements with their attributes.

Example:

<input type="text" />
<input type="email" name="email" id="email" required />
Enter fullscreen mode Exit fullscreen mode

CSS:

input[required] {
  border-color: blue;
}
Enter fullscreen mode Exit fullscreen mode
  • [attr=value]

Selects the elements with their attribute name and attribute value.

Example 1:

<input type="text" />
<input type="email" name="email" id="email" />
Enter fullscreen mode Exit fullscreen mode

CSS:

input[type="email"] {
  border: 1px solid blue;
}
Enter fullscreen mode Exit fullscreen mode

This will change the style of the email type inputs.

Example 2:

<a href="/">Click me!</a>
<a href="/" target="_blank">Click me!</a>
Enter fullscreen mode Exit fullscreen mode

CSS:

a[target="_blank"] {
  text-decoration: overline;
}
Enter fullscreen mode Exit fullscreen mode
  • [attr~=value]

Selects elements containing a whole word. For example:

<p>This is paragraph.</p>
<p class="special">This is paragraph.</p>
<p>This is paragraph.</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

p[class~="special"] {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode

This will change the color of the <p> element containing special class name.

  • [attr*=value]

Selects elements containing a substring of a word. For example:

<img src="logo.png" alt="logo" />
<img src="image.png" alt="picture" />
<img src="logo.png" alt="logo" />
Enter fullscreen mode Exit fullscreen mode

CSS:

img[src*="logo"] {
  border: 2px solid red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the style of all the image element that contains “logo” in its src attribute value.

  • [attr$=value]

Selects elements with an attribute value ending with a specific word. For example:

<img src="logo.png" alt="logo" />
<img src="image.png" alt="picture" />
<img src="logo.jpg" alt="logo" />
Enter fullscreen mode Exit fullscreen mode

CSS:

img[src$=".png"] {
  border: 2px solid red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the style of all the image elements which have their src attribute value ending with “.png”.

  • [attr^=value]

Selects elements with an attribute value starting with a specific word. For example:

<a href="www.example.com">Example</a>
<a href="https://example.com">Example</a>
Enter fullscreen mode Exit fullscreen mode

CSS:

a[href^="https:"] {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the style of all the <a> elements which have their href attribute value starting with “https:”.

Grouping Selectors

You can group multiple selectors to apply the same style to them.

For example:

<h1>This is first heading.</h1>
<h2>This is second heading.</h2>
<h3>This is third heading.</h3>
<p>This is paragraph.</p>
Enter fullscreen mode Exit fullscreen mode

CSS:

h1, h2, p{
  color: purple;
  font-style: italic;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Throughout this blog post, we have learned about the CSS selectors to style our web page elements specifically, using different types of selectors.

We have categorized the selectors as basic selectors, combinators, pseudo-classes, pseudo-elements and attribute selectors.

By embracing these selectors, you can craft web pages that not only look visually appealing but also offer a seamless and enjoyable user experience.

Thanks for reading.

For more content like this click here!

Keep Coding!
Buy Me A Coffee

Top comments (0)