What Is a CSS Selector?

Oct 19, 2023 | Test Automation Insights

What Is a CSS Selector?

 

Building a website from scratch is the surest way to completely control its look and feel. But to do that, you need knowledge of HTML, CSS, and JavaScript. One way to shorten your development time is by using CSS selectors to customize your site. We’ll cover exactly what a CSS selector is and discuss the intricacies of using them in web development. 

CSS Selectors 101

Cascading Style Sheet (CSS) is a design language that makes web pages look presentable. Everything banner images to a menu’s border is typically done using CSS. And the heart of CSS code is its selectors.

What Is a CSS Selector?

CSS selectors allow developers to target and style webpage HTML elements. You use them to add color, shape, and style to your site. 

CSS selectors let you determine which elements you want to apply CSS styling rules to, which define their look and feel — important things to account for when performing web UI tests.

The Role of CSS Selectors in Web Styling

Selectors make styling websites more manageable. You can use selectors in CSS in two different ways:

  • Add CSS selectors to a webpage’s <head> section
  • Store CSS styles and selectors in a separate document and link to it from the <head> section of a webpage

Many designers find it easier to reference CSS selectors from a separate document. That allows for a cleaner separation of the HTML code and the CSS language. Here’s an example of the link you would include in the <head> section of the HTML layout:

“<link rel=”stylesheet” href=”style.css”>” 

Common Use Cases for CSS Selectors

Before diving deeper, let’s talk about CSS element selectors, also called universal selectors. Think of them as HTML CSS selectors. They target all instances of specific HTML elements. 

If you wanted to style all the paragraph elements of a webpage, you would use the p selector as shown below:

p {
  font-size: 18px;
  color: #334;
}

The above basic CSS selector element adds CSS property values that set the font size of all paragraphs to 18 pixels and the text color to a nice blue-magenta color — this is just one example of how you can use a CSS element selector. If you want to use identical CSS for more than one element, you can combine multiple CSS selectors into a list. 

For example, if you want to apply the same CSS styling to both <h1> and <h2> headers, you set up a CSS rule for multiple types of selectors into a single list:

h1, h2 {
 color: blue;
}

The white space before and after a comma is valid. Some choose to put selectors on a new line to make the rule more readable. 

Types of CSS Selectors

Now that we have a basic understanding of using a selector in CSS, let’s explore some simple CSS selector examples. These six common CSS selectors enable you to select different web page element groups. 

📌 Type Selectors

A CSS type selector lets you apply consistent styling to HTML elements on your page. That way, you can have a uniform look for your headings, paragraphs, and list items, giving your webpage a cohesive look and feel. 

📌 Class Selectors

CSS class selectors let web developers target HTML elements using a class attribute denoted by a period (.), then the class name within a CSS stylesheet. 

You associate HTML elements with a class selector by adding the “class” attribute to the element’s tag and specifying its name:

.new-class {
               /* Add CSS styling */

You can then apply the class above to your HTML:

<p class=" new-class">We styled this paragraph using the class we created. </p>

Class selectors give you fine-grained control over styling, which is important for making certain elements look different from those of the same type within the same webpage. You can use classes to style buttons differently:

.main-btn {
  background-color: #0078d4;
  color: white;
  padding: 15px 25px;
}

.second-btn {
  background-color: #eee;
  color: #333;
  padding: 10px 20px;
}

📌 ID Selectors

ID selectors are CSS mechanisms that let developers target single HTML elements with a unique identifier. They contain a hash symbol (#) followed by the ID name. You associate HTML elements with CSS ID selectors by adding the “id” attribute to the tag and specifying the ID name:

#single-element {
  /* CSS styles go here */
}

You can then apply the above ID selector to your HTML:

<div id="single-element">We styled this individual element with a unique ID.</div>

📌 Attribute Selectors

Developers use CSS attribute selectors to target HTML elements based on their attributes’ presence or specific value. They give you a way to apply styles that meet specific attribute criteria. You set up attributes using square brackets ([…]). They consist of an attribute name and an optional value or value pattern enclosed in quotation marks:

a[target="_blank"] {
  /* CSS styles go here */
}

You would use the CSS attribute in your HTML to let you click a link and visit a new site:

<a href="https://example.com" target="_blank">Visit Example</a>

Using the above type of CSS attribute selector ensures the style only applies to links with a target attribute set to “_blank.”

📌 Pseudo-Classes

Pseudo-classes target elements based on their state or position within the document object model (DOM). You designate pseudo-classes using a colon ( : ) followed by the CSS pseudo-class’s name. A pseudo selector applies styling to elements in a particular state or context, like links being hovered over, checked checkboxes, or elements that are the first child of a parent. 

When it comes to a CSS ID vs. class, the biggest difference is that IDs target single elements, while classes cover multiple elements.

a:hover {
  /* CSS styles go here */
}

You would use the above pseudo-class in HTML like this to apply a specific style when someone hovers over a link:

<a href="#">Hover over this link!</a>

Pseudo-classes are typically used in the following instances:

  • Styling form elements
  • Creating navigation menus
  • Targeting elements in a specific context

📌 Combinators

CSS combinator selectors define relationships or connections between HTML elements, letting developers target elements based on where they fall in the DOM. You can create complex selectors to pinpoint elements for styling. There are four main types of CSS selector combinators. 

Whitespace (Descendant Combinator)

A whitespace character represents the descendant combinator. It selects all elements descended from a specific element, regardless of how deeply they’re nested in an HTML structure. 

.parent_element p {
  /* CSS styles go here */
}

The above example selects all <p> elements that descend from an element using the class “parent_element.” 

Child Combinator

The child combinator is represented using the ( >) symbol. It selects elements that are direct children of a specific component. Below is an example of how to use the CSS operator.

.parent_element > p {
  /* CSS styles go here */
}

The above selects only the <p> elements that descend from the children of an element with a class “parent_element.” 

Adjacent Sibling Combinator 

Represented by the ( + ) symbol, the adjacent sibling combinator selects elements immediately preceded by a specified element. You use the CSS + selector as shown below.

H3 + p {
  /* CSS styles go here */
}

The above example selects all <p> elements directly following <h3> elements. It won’t apply styling to <p> elements not preceded by an <h3>.

General Sibling Combinator

The general sibling combinator uses the ( ~ ) symbol to select elements that are siblings of specific elements and share the same parent. 

H3 ~ p {
  /* CSS styles go here */
}

The above selects all <p> elements with the same parent as an <h3> element. 

Developers typically use CSS combinators to:

  • Apply fine-grained styling to elements with precision
  • Set up complex layouts and designs
  • Target interactive elements on web pages
  • Enhance accessibility by targeting specific elements within forms or tables

The Importance of CSS Selectors in Web Development

CSS elements give you complete control over web pages’ responsiveness, interactivity, and visual appeal. Mastering CSS selectors helps you:

  • Maintain consistency in the design and layout of web pages
  • Efficiently style web pages
  • Create responsive designs
  • Make pages more accessible
  • Separate content from web page behavior

❗️ Why Specificity Matters

Specificity is a vital aspect of CSS selectors. They let you decide which style rules apply when two or more rules target the same element. It helps browsers determine what style rule gets precedence when they conflict. 

Selectors given a higher specificity override those with a lower specificity. This is calculated based on the combination of selectors used. 

For example, ID selectors automatically have a higher specificity than class selectors, which have a higher specificity than element selectors. Here’s a basic overview of the CSS specificity hierarchy:

  1. Inline styles
  2. Identifiers (ID)
  3. Classes, pseudo-classes, and attributes
  4. Elements and pseudo-elements

The sample HTML page below illustrates how it works:

<html>
<head>
    <style type= "text/css">
        H2 {
            background-color: white;
            color: blue;
        }
        #second {
            background-color: white;
            color: green;
        }
        .third {
            background-color: gray;
            color: blue;
        }
        #fourth {

            color: black;

        }
        .fifth {
            color: orange;
        }
    </style>
</head>

<body>
    <h2 id="second" class="fourth">
        ID = highest priority.
    </h2>
    <h2>
        Element selectors rank at the bottom of the priority list.
    </h2>
    <h2 class="fifth">
        Classes are ranked with a higher priority versus element selectors. 
    </h2>
    <h3 style="color: green;" id="fourth" class="fifth">
        Inline CSS is at the top of the priority list. </h3>
 </body>
 </html>

You can also style multiple elements using a CSS grouping selector, created by adding a comma after each element:

img, p, h2 {
/* CSS Styling Goes Here */
}

Streamline Your Entire Testing Processes With a CSS Generator Tool

Ranorex provides tools to help streamline the web development process. We also help you automate web testing to help you confirm your site’s functionality. Check out the Ranorex Selocity browser extension, designed to speed up your selector to element creation.x

 

Related Posts:

5 Software Quality Metrics That Matter

5 Software Quality Metrics That Matter

Which software quality metrics matter most? That’s the question we all need to ask. If your company is dedicated to developing high-quality software, then you need a definition for what “high-quality” actually looks like. This means understanding different aspects of...

The Ins and Outs of Pairwise Testing

The Ins and Outs of Pairwise Testing

Software testing typically involves taking user requirements and stories to create test cases that provide a desired level of coverage. Many of these tests contain a certain level of redundancy. Traditional testing methods can lead to a lot of wasted time and extend...