• Ramotion /
  • Blog /
  • Exploring CSS Selector: A Comprehensive Guide

Exploring CSS Selector: A Comprehensive Guide

A CSS selector is the most integral part of a CSS syntax used to select and target HTML elements and CSS styles to them.

Written by RamotionApr 18, 202312 min read

Last updated: Feb 21, 2024

Definining CSS Selector

All websites on the internet are made up of old and new versions of Hypertext Markup Language (HTML) that essentially control almost all the elements n a webpage, such as text, form fields, images, and videos. HTML has been around for over 30 years and is still used as a fundamental language for annotating a document to explain what sections in a web page should be formed and how they should be presented.

However, using HTML alone is limited in design and layout capability, often producing boring web pages. While it's usable in forming or describing basic content, the appearance of raw HTML on web pages could be more appealing and modish when presented to website visitors.

This is where Cascading Stylesheets (CSS) come to the rescue. CSS enables web professionals to create stunning presentations of content when building websites. With CSS, website designers and developers can achieve many things that are either difficult or impossible using standard markup language alone. Whether it's color, background, shapes, transition, and various animation effects, CSS can provide you with all the necessary selectors, declarations, and properties to help you build compelling, engaging, and beautiful websites.

Regardless of the type of style sheet you are creating, each CSS block uses different types of selectors to specify which elements a style sheet rule should apply to, whether it's a heading, paragraph, image, etc. Selectors are considered one of the underlying features of CSS and one of the beginner topics that need to be learned if you are starting.

CSS selectors are the most integral part of CSS syntax as they are the foundational concept of how to target specific content and style in styles HTML elements on a web page in a distinct manner. Selectors enable CSS web designers and developers to declare unique specific rules for certain HTML elements, or groups of elements, based on their attributes, properties, and relationships to other elements.

Using CSS selectors efficiently, you can write concise and clean CSS that can style elements with minimal lines of CSS code and is easy to read and understand. When learning CSS, it's essential to understand that CSS rule sets have two parts: the selector and the declaration block. As a general rule, declaration blocks are placed inside a selector with the key-value-based format and are used to define the style applied to the web element or tag.

Without any element selectors, it's impossible to target and style specific HTML elements on a web page or control specific styles for certain web elements based on their position or relationship to other elements. Selectors allow web professionals to create sophisticated, multi-level stylesheets that can target and style almost any content on a web page.

CSS selectors are flexible, allowing users to build dynamic, structured styles that can adapt to various screen sizes, devices, and platforms using media queries, pseudo class selectors, and other advanced selector techniques. Understanding the different types of selectors available and how to combine them enables you to build sophisticated CSS that creates responsive and interactive web pages that look great on any device.

A CSS selector selects an HTML element based on their CSS id selector, class name, class selector, class type, class attribute, pseudo element selectors, and combination selectors. All the HTML elements in a webpage use selectors to target specific HTML elements and apply styles, such as changing the color, font size, or background color.

For example, if you want to add a CSS rule to a paragraph or p element, you can use the p element selector to select elements with paragraph tags on your HTML code. To simplify, a CSS selector targets HTML elements with its opening and closing (<>) tags stripped off.

Here’s a paragraph CSS element selector within a CSS rule:

p {color: grey; }

Copy

This CSS rule means that all the HTML elements with paragraph element will have the color grey applied to them.

A CSS selector can be utilized through five main types of selectors:

  • Element selector
  • Id selector
  • Class selector
  • Attribute selector
  • Universal selector

How CSS Selectors Work

Selectors are CSS building block features that target specific elements in an HTML document and apply styles to them. CSS selectors allow you to apply rules to specific elements based on their specified attributes, relationships with other elements, and other factors, such as using complex selector combination, targeting parent element with the same style definitions, etc.

Here’s a general syntax when working with CSS selectors:

[element selector | class selector | id selector | attribute selector | descendant selector ] {
  property: value;
}
Copy

As an overview, CSS selectors work in the following sequence:

Phase #1: The HTML document gets parsed to create a Document Object Model (DOM) tree.

Phase #2: CSS rules are applied to the HTML document in the DOM tree.

Phase #3: The browser applies the styles to the specific element / unique element that the selector matches.

Phase #4: Selected elements get all the rules the selector sets. In some cases, if multiple selectors match the same selected element, it gets the styles from the most specific selector. The CSS id selector, CSS class selector, and element types in a selector determine its specificity.

Phase #5: In terms of CSS rule or style conflict, the last rule gets applied to the targeted element.

CSS Selectors Importance

CSS selectors provide several benefits when managing stylesheets and rules for each specific, multiple, and related elements.

Selectors are important in CSS coding for the following reasons:

  • It makes it easy to target all the elements on a web page and apply styles.
  • It allows you to write efficient and clean code by targeting only the elements that need to be styled.
  • It lets you separate styles on different web components based on their uses on a web design layout.
  • It enables you to write clean and easy-to-maintain code by creating a consistent and organized style rule that is easy to update and modify.

Types of Selectors

Below, we'll start looking at how to use different selectors to specify which elements a style sheet rule can apply to. Each selector can select different elements groups and style them based on their specificity.

Basic CSS Selectors

Basic CSS selectors are the simplest and easiest selectors to use as they only select instances of a particular HTML element or tag, class attribute, and id attribute.

1. Element Selector

A CSS element selector matches all instances of a particular HTML element based item in a web page. Element selectors are often used in styling plain HTML sections or blocks without any complex layout or design.

For example, to target p elements on a web page, write the element name and define the properties and values you want it to be styled. See the below example:

p {
  color: black;
  font-size: 16px;
}
Copy

2. ID Selector

Compared to the CSS element selector, the id selector selects a single HTML element with a specific id attribute. An id selector selects matches an id attribute containing a specified attribute value using a hash or pound sign (#).

For example, to target the element with the id "main-header", you would use the selector #my-header:

<h1 id="my-header">The Best Headline Ever</h3>

#first-headline {
  color: yellow;
  font-size: 35px;
}
Copy

The id selectors should be unique within a document. This selector should only apply to one unique element.

3. Class Selector

The CSS class selector is the most widely used selector in everyday coding. Compared to the id selector, the CSS class selector targets one or multiple HTML elements simultaneously with a specific class attribute regardless of their HTML tag names whose value matches the one you specify in the class selector.

The CSS class selector uses a period or full stop preceding the class name or class attribute.

For example, to target all p elements with the class "my-class," you would use the selector ".my-class."

<p class="my-first-class"> This is a good paragraph. </p>

.my-first-class {
    color: #dedede;
    font-size: 12px;
    font-style: italic;
}
Copy

By default, all p elements will have the same style definitions. You can also use multiple class selectors in an element:

<p class="my-first-class text-center font-small"> This is a good paragraph. </p>

Copy

Advanced CSS Selectors

Advanced CSS Selectors are selectors that specifically target HTML elements based on attributes or states, which helps create more complex and dynamic styles.

1. Attribute Selector

CSS attribute selectors allow you to use an element's attributes, including its attribute value in the selector. Attribute selectors allow you to target elements based on their attributes, such as a class, id, alt, or href attribute.

Attribute selectors match the style definitions of elements based on both the presence of an attribute and the precise and complete value of an attribute.

Attribute selectors come in several varieties, such as simple attribute selectors, exact attribute value selectors, partial attribute value selectors, and substring attribute selectors.

To cite a simple example, a match can still occur in the following code if a p element has a class or any class.

<p class="sub-text">This are subtext paragraph here</p>

p[class] 
{
   font-size: 14px;
   font-style: italic;
}
Copy

In the example above, no class name is defined; instead, we specify only the class attribute, meaning it will select elements with any class.

Another type of attribute selector matches the "value." To cite another example, take a look at the anchor element below.

<a rel="nofollow" href="http://www.ilovetotravel.com/">Book A Flight Now</a>

a[rel="nofollow"] {
   font-weight: bold;
}
Copy

This will match all anchor elements with a rel attribute containing a "nofollow" value.

2. Pseudo-Class Selector

Pseudo-class selectors enable you to target pseudo elements based on their states, such as hover, active, first child (first element), or parent element. All pseudo-classes are structural and dependent on document flow to select elements in an intrinsical pattern. Pseudo classes can be combined with other selectors to create even more specific targeting.

Here's a basic example of a CSS pseudo-class selector using span elements:

span:hover {
  color: green;
}
Copy

In the example above, the :hover pseudo-class is used to target span elements when the user hovers over their mouse. When this action is triggered, the text color of the span element will change to green.

3. Pseudo-Element Selector

In addition to pseudo-classes, CSS selectors also have the concept of pseudo-element. This refers to the keyword that specifies a unique style for a specific part or chunk of an HTML element. Pseudo-elements are used to add rules for a particular part of an element that cannot be targeted with a regular CSS selector, such as the first letter of a paragraph, the first line of a headline, or the content before or after an element.

In the days of CSS1 and CSS2, pseudo-elements used single colons (:) symbols just as pseudo-classes were, but in CSS3, pseudo-elements use double colons (::) to differentiate them from pseudo-classes.

Below are the four main pseudo-elements:

  • ::before
  • ::after
  • ::first-letter
  • ::first-line

As an example of how to use the pseudo-element selector, the code below used the ::before pseudo-element to add content before an element:

h2::before {
  content: "Some content goes here";
  font-size: 25px;
  font-family: 'Poppins', sans;
}
Copy

In the example above, the CSS rule applies the rules to the content before the h2 element, indicating that the text is before the paragraph element.

4. Universal Selector

The CSS universal selector is represented by an asterisk and acts like a wildcard that matches or selects all element types in the HTML document. Unlike id and class selectors, a CSS universal selector can apply rules to all elements without any class name or tag references, regardless of the element type or class.

Below is an example of how to use the CSS universal selector using the asterisk symbol to apply a general style to all elements on a web page:

* {
  margin: 0;
  padding: 0;
}
Copy

In the CSS code above, the CSS universal selector asterisk (*) symbol applies a margin and padding of zero to all elements, which can help create a consistent layout across an entire website.

Basic vs. Advanced CSS Selectors

Both basic vs. advanced CSS selectors are essential in every CSS coding workflow as they select different types of elements ranging from plain HTML tags to complex attributes and values.

Basic selectors are the simplest to use to target HTML elements based on their tag name, class, or id. For example, if you want to target all p elements on a web page, you would use the selector p. In some cases, if you want to select multiple elements with the same class name, you can target these elements via a class selector.

On the other hand, advanced CSS selectors provide more flexibility and control when adding styles to a specific element or even a part or chunk of an HTML element. For example, if you want to target only the first line of p elements or every paragraph, you would use the p::first-line selector.

While sometimes it's not too obvious to perceive the difference between the basic and advanced CSS selectors, it’s essential to note that CSS selectors using ids and classes are way faster (mainly the ids) than others, such as a general sibling selector or pseudo selector. This is extremely helpful when writing CSS codes for complex websites.

Group Selectors: What is it and why it’s important

The group selector concept, or simply grouping CSS selectors, defines many selectors to apply the same styles simultaneously. The grouping selector concept can save time and make your code cleaner, more concise, and easy to maintain.

Instead of defining each selector as a distinct style in your CSS file, with the CSS group selector, you can combine the selectors via commas. With the group selector method, you can group almost any basic and advanced CSS selectors to form a much more efficient code rather than repeating CSS codes.

How does CSS Group Selector Works

To group selector in your CSS file, list the selectors you want to group by separating them with commas (,). As an example, if you want to group selector that includes the basic HTML elements, such as paragraphs and headings, you can list them as follows:

p, h1, h2, h3, h4, h5, h6 {
   color: #3e3e3e;
   font-family: 'Lato', sans-serif;
}
Copy

In the CSS group selector example above, all paragraphs and headings on the web page will have the font family set to Lato or a similar sans-serif font and the color assigned to dark gray (#3e3e3e).

To take the group selector concept even further, you can also add class names to your CSS code, as seen below:

p, h1, h2, h3, h4, h5, h6, .my-class {
   color: #3e3e3e;

   font-family: 'Lato', sans-serif;
}
Copy

By grouping selector, you can apply the same CSS rules to multiple elements, making your CSS coding workflow faster and more efficient.

In Summary

A stylesheet consists of one or more rules describing how web page elements should look. Each CSS code block includes a selector and a declaration of CSS styles. Selectors can stand individually or be grouped as a comma-separated list.

Selectors are an integral part of every CSS code block as it's the only way to target specific HTML elements and apply styles to each. Without CSS selectors, targeting specific or group elements via the grouping selector method and building a visually appealing, engaging, and effective website is impossible.

Share: