DEV Community

Cover image for Mastering CSS3 Selectors: A Complete Guide with Examples
Eleftheria Batsou
Eleftheria Batsou

Posted on • Originally published at eleftheriabatsou.hashnode.dev on

Mastering CSS3 Selectors: A Complete Guide with Examples

Introduction

In this article, we will talk about CSS3 selectors, a really powerful tool for everyone who wants to do more while writing less. Whether you're just starting or brushing up your skills, this guide will walk you through the basics to the advanced stuff.

Ready to level up your CSS skills? Let's get started!

Basic CSS3 Selectors

Selectors are the tools we use to pick out certain elements from the HTML tree. Basic CSS3 selectors, as the name suggests, are the fundamental ones that every developer should have in their toolkit. They include Type , Class , ID , Universal , and Attribute selectors. Let's dive deeper into each of these.

Type Selectors

These selectors target HTML elements based on their tag name. For example, p { color: blue; } will style all paragraph elements in blue.

Class Selectors

These selectors target HTML elements based on their class attribute. For instance, .alert { color: red; } will style all elements with the class "alert" in red.

ID Selectors

These selectors target a unique element that has the specific id attribute. For example, #navbar { background-color: black; } will style the element with the id "navbar" with a black background.

Universal Selectors

These selectors target all elements on a page. For instance, * { margin: 0; } will remove the margin from all elements on the page.

Attribute Selectors

These selectors target elements based on their attribute and value. For instance, a[href="https://google.com"] { color: blue; } will style all links directing to Google in blue.

Short Coding Examples

  • Type Selector : h1 { color: green; } will color all h1 headers green.

  • Type Selector : p { font-size: 16px; } will select all paragraph elements (<p>) and set their font size to 16 pixels.

  • Class Selector : .info { font-size: 18px; } will set the font size of all elements with the class "info" to 18px.

  • Class Selector : .highlight { background-color: yellow; } will select all elements with the class "highlight" and set their background color to yellow.

  • ID Selector : #footer { padding: 20px; } will add a padding of 20px to the element with the id "footer".

  • ID Selector : #header { height: 60px; } will select the element with the ID "header" and set its height to 60 pixels.

  • Universal Selector : * { font-family: Arial, sans-serif; } will set the font of all elements to Arial.

  • Universal Selector : * { box-sizing: border-box; } will select all elements on the page and set their box-sizing property to "border-box", which includes padding and border in the element's total width and height.

  • Attribute Selector : img[alt] { border: 2px solid black; } will add a border to all images that have an alt attribute.

  • Attribute Selector : input[type="text"] { width: 100%; } - This will select all input elements with the type "text" and set their width to 100% of their parent container.

Pseudo-Class Selectors

Pseudo-class selectors are a powerful feature in CSS that allows us to select and style elements based on their state or position in the document structure rather than their type, attribute, or class. They are instrumental in creating dynamic and responsive designs.

Dynamic Pseudo-Classes

Dynamic pseudo-classes include styles that change based on user interaction. For example, a:hover { color: red; } will change the color of links to red when hovered over.

Structural Pseudo-Classes

Structural pseudo-classes select elements based on their position in the document structure. For instance, p:first-child { font-weight: bold; } will make the first paragraph bold within its containing element.

Negation Pseudo-Class

The negation pseudo-class, :not(), excludes a specific element from a selection. For example, div:not(.highlight) { background-color: yellow; } will change the background color of all divs to yellow, except those with class "highlight".

Input Pseudo-Classes

Input pseudo-classes are used to style form elements based on their state. For example, input:disabled { opacity: 0.5; } will style disabled input fields with half opacity.

Short Coding Examples

  • Dynamic Pseudo-Class : a:focus { outline: none; } will remove the focus outline from links when they are clicked or navigated to via keyboard.

  • Dynamic Pseudo-Class : button:active { background-color: red; } will change the background color of a button to red when it is being clicked.

  • Structural Pseudo-Class : li:last-child { color: red; } will color the last list item red in every list.

  • Structural Pseudo-Class : p:nth-child(2) { color: blue; } will select the second paragraph within its parent element and color the text blue.

  • Negation Pseudo-Class : p:not(.no-border) { border: 1px solid black; } will add a border to all paragraphs that do not have the class "no-border".

  • Negation Pseudo-Class : div:not(#exclude) { border: 1px solid green; } will add a border to all div elements that do not have the id "exclude".

  • Input Pseudo-Class : input:checked { background-color: green; } will change the background color of checked input elements to green.

  • Input Pseudo-Class : input:valid { border: 2px solid green; } will add a green border to all valid input fields based on their validation rules.

Pseudo-Class Elements

Pseudo-elements selectors allow us to style certain parts of a document. They can be utilized to style the first letter, or line, of an element or insert content before or after an HTML element.

Before and After Pseudo-elements

These pseudo-elements let us insert content before or after the content of an element.

Example:

p::before { 
content: "Read this - "; 
color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will insert "Read this - " before the content of every paragraph and color it red.

First-letter and First-line Pseudo-elements

These pseudo-elements are used to style the first letter or first line of a text block.

Example:

p::first-letter { 
font-size: 20px; 
color: blue;
}
Enter fullscreen mode Exit fullscreen mode

This will make the first letter of every paragraph 20px in size and blue in color.

Short Coding Examples

  1. p::after { content: "*"; } - This will add an asterisk (*) after each paragraph.

  2. .warning::before { content: "WARNING: "; font-weight: bold; color: red; } - This will add "WARNING: " before the content of elements with the class "warning". The text will be bold and red.

  3. blockquote::first-line { font-weight: bold; } - This will make the first line of every blockquote bold.

  4. div::first-letter { text-transform: uppercase; } - This will transform the first letter of every div into uppercase.

  5. h1::after { content: ""; color: green; } - This will add a green check mark after every h1 element.

Codepen Examples

Pseudo-elements and pseudo-classes are a few of my favorite selectors and to really understand them I'd suggest you do a lot of practice.

Here are a few examples on Codepen that you can experiment with:

Example 1

Tutorial

Example 2

Tutorial

Example 3

Tutorial

These examples seem simple but if you check the code you'll notice they are made with very few pseudo classes!

Combinator Selectors

Combinator selectors in CSS are a powerful way to select specific elements that fulfill certain relational criteria with other elements. These selectors allow us to target elements based on their relationship in the document tree, such as if an element is a child, descendant, or sibling of another element.

Descendant Combinators

A descendant combinator is denoted by a space. It selects elements that are descendants of a certain element.

Examples:

div p { color: blue;}
Enter fullscreen mode Exit fullscreen mode

This will select all <p> elements that are descendants of a <div> element, and color the text blue.

div p { background-color: yellow;}
Enter fullscreen mode Exit fullscreen mode

This will select all <p> elements that are descendants of a <div> element, and give them a yellow background.

Child Combinators

A child combinator is denoted by >. It selects elements that are direct children of a certain element.

Examples:

div > p { color: blue;}
Enter fullscreen mode Exit fullscreen mode

This will select all <p> elements that are direct children of a <div> element, and color the text blue.

div > p { border: 1px solid red;}
Enter fullscreen mode Exit fullscreen mode

This will select all <p> elements that are direct children of a <div> element, and give them a border.

Adjacent Sibling Combinators

An adjacent sibling combinator is denoted by +. It selects an element that is directly after another specific element.

Example:

div + p { color: blue;}
Enter fullscreen mode Exit fullscreen mode

This will select any <p> element that is directly after a <div> element, and color the text blue.

General Sibling Combinators

A general sibling combinator is denoted by ~. It selects elements that are siblings of a certain element.

Example:

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

This will select all <p> elements that are siblings of a <div> element, and color the text blue.

Advanced CSS3 Selectors

Advanced CSS3 selectors provide more precise targeting capabilities than basic selectors. These include attribute selectors with various matchers and nth-child/nth-of-type selectors.

Attribute Selectors with Various Matchers

Attribute selectors can be used with various matchers to select elements based on specific conditions related to their attributes.

Example:

input[type="text"] { 
color: blue;
}
Enter fullscreen mode Exit fullscreen mode

This will select all input elements with the type attribute of "text" and color the text blue.

Nth-child and Nth-of-type Selectors

The nth-child and nth-of-type selectors are used to select elements based on their position in the parent element.

Example:

p:nth-child(2) { 
color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will select the second child paragraph of its parent element and color the text red.

Short Coding Examples

  1. Attribute Selector with Matcher: a[href^="https"] {font-style: italic;} - This will select all links that have an href attribute that starts with "https" and make the text italic.

  2. Attribute Selector with Matcher: input[type$="text"] {background-color: yellow;} - This will select all input elements that have a type attribute that ends with "text" and give them a yellow background.

  3. Nth-child Selector: li:nth-child(odd) {background-color: grey;} - This will select all odd-numbered list items and give them a grey background.

  4. Nth-of-type Selector: p:nth-of-type(3n) {font-weight: bold;} - This will select every third paragraph and make the text bold.

Best Practices for Using CSS3 Selectors

  1. Use the Right Selector : The key to using CSS3 selectors effectively is to use the right selector for the job. For instance, use class selectors when you want to style a group of elements and ID selectors for unique elements.

  2. Avoid Over-Specification : Over-specifying selectors can make your CSS hard to maintain. Stick to simple selectors as much as possible.

  3. Use Shorthand Properties : Shorthand properties can make your CSS cleaner and easier to read. For example, use margin: 0 auto; instead of margin-top: 0; margin-right: auto; margin-bottom: 0; margin-left: auto;.

  4. Group Selectors : If multiple selectors share the same style declaration, group them together to keep your CSS DRY (Don't Repeat Yourself).

  5. Comment Your Code : Commenting your CSS can help you and others understand what your code does, especially when using complex selectors.

  6. Use Pseudo-classes and Pseudo-elements : These can help you target elements based on their state or position in the document, which can make your CSS more dynamic and responsive.

  7. Keep Specificity Low : Overly specific selectors can lead to specificity wars, making it hard to override styles later. Keep your specificity as low as possible.

  8. Test Across Different Browsers : Different browsers can interpret CSS selectors differently. Always test your CSS across different browsers to ensure consistency.

Conclusion

In conclusion, selectors, ranging from basic type, class, and ID selectors to advanced pseudo-classes, pseudo-elements, and combinators, provide a powerful toolset for styling HTML elements. By understanding and applying these selectors, you can create dynamic, responsive, and aesthetically pleasing websites.

However, it's important to follow best practices such as using the right selector for the job, avoiding over-specification, grouping selectors, and testing across different browsers to ensure the maintainability and consistency of your CSS code.


👋 Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

🥰 If you liked this article, consider sharing it.

🔗 All links | X | LinkedIn

Top comments (0)