Home > Article > Web Front-end > Mastering CSSelectors: A Complete Guide with Examples
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!
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.
These selectors target HTML elements based on their tag name. For example, p { color: blue; } will style all paragraph elements in blue.
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.
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.
These selectors target all elements on a page. For instance, * { margin: 0; } will remove the margin from all elements on the page.
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.
Type Selector : h1 { color: green; } will color all h1 headers green.
Type Selector : p { font-size: 16px; } will select all paragraph elements (
) 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 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 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 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.
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 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.
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-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.
These pseudo-elements let us insert content before or after the content of an element.
Example:
p::before { content: "Read this - "; color: red; }
This will insert "Read this - " before the content of every paragraph and color it red.
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; }
This will make the first letter of every paragraph 20px in size and blue in color.
p::after { content: "*"; } - This will add an asterisk (*) after each paragraph.
.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.
blockquote::first-line { font-weight: bold; } - This will make the first line of every blockquote bold.
div::first-letter { text-transform: uppercase; } - This will transform the first letter of every div into uppercase.
h1::after { content: ""; color: green; } - This will add a green check mark after every h1 element.
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 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.
A descendant combinator is denoted by a space. It selects elements that are descendants of a certain element.
Examples:
div p { color: blue;}
This will select all
elements that are descendants of a
div p { background-color: yellow;}
This will select all
elements that are descendants of a
A child combinator is denoted by >. It selects elements that are direct children of a certain element.
Examples:
div > p { color: blue;}
This will select all
elements that are direct children of a
div > p { border: 1px solid red;}
This will select all
elements that are direct children of a
An adjacent sibling combinator is denoted by +. It selects an element that is directly after another specific element.
Example:
div + p { color: blue;}
This will select any
element that is directly after a
A general sibling combinator is denoted by ~. It selects elements that are siblings of a certain element.
Example:
div ~ p { color: blue;}
This will select all
elements that are siblings of a
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 can be used with various matchers to select elements based on specific conditions related to their attributes.
Example:
input[type="text"] { color: blue; }
This will select all input elements with the type attribute of "text" and color the text blue.
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; }
This will select the second child paragraph of its parent element and color the text red.
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.
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.
Nth-child Selector: li:nth-child(odd) {background-color: grey;} - This will select all odd-numbered list items and give them a grey background.
Nth-of-type Selector: p:nth-of-type(3n) {font-weight: bold;} - This will select every third paragraph and make the text bold.
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.
Avoid Over-Specification : Over-specifying selectors can make your CSS hard to maintain. Stick to simple selectors as much as possible.
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;.
Group Selectors : If multiple selectors share the same style declaration, group them together to keep your CSS DRY (Don't Repeat Yourself).
Comment Your Code : Commenting your CSS can help you and others understand what your code does, especially when using complex selectors.
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.
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.
Test Across Different Browsers : Different browsers can interpret CSS selectors differently. Always test your CSS across different browsers to ensure consistency.
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
The above is the detailed content of Mastering CSSelectors: A Complete Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!