Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

CSS Attribute Selector: Use This Powerful Tool For HTML Styling

The CSS Attribute Selector is a potent feature within Cascading Style Sheets, offering developers a potent and targeted approach to styling HTML elements. In this comprehensive guide, we delve into the intricacies of attribute selectors, uncovering their fundamental syntax, advanced techniques, and diverse applications. These selectors empower developers to apply styles selectively based on attribute values, providing a dynamic and responsive means to enhance the visual presentation of web pages also this guide equips developers with the skills to optimize performance and leverage the full potential of CSS Attribute Selectors in real-world scenarios.

Prerequisites

In other to follow this guide, it’s expected that you have a basic knowledge of HTML and CSS. If you need help with HTML and CSS, please visit MDN.

Basic Syntax of Attribute Selectors

CSS attribute selector provides a means to select HTML elements based on their attribute names, with options for defining an attribute value or substring value match. The basic syntax of the attribute selector is denoted by the square bracket symbol [ ] which encapsulates the name of the HTML attribute with other various options.

Here’s a snippet showing the basic syntax of the Attribute selector:

/* Select all elements with a href attribute */
[href] {
  color: purple;
}

/* Select all elements with the class attribute value of "purecode-block" */
[class="purecode-block"] {
  padding: 20px 10px;
}

/* Select all anchor elements with a href attribute value as https://purecode.ai/  */
a[href="https://purecode.ai/"] {
   color: purple;
}

Types of attribute selector

There are seven different types of attribute selectors, each with a different syntax. However, the basic syntax is still used, where in the square brackets, there is an attribute name that equals some attribute value. But what makes the difference is the symbol used along the equal (=) sign, which changes the way HTML elements are selected.

1. [attribute] selector

The [attribute] selector is used to select all the matching elements based on the attribute name specified, allowing us to apply CSS properties to does elements selected.

Example of [attribute] selector

For example, let’s say we have a list of beverages, and we’ve identified the beverages we have in our store with the data-my-shop attribute from the list.

To style the elements with the attribute data-my-shop using the [attribute selector] we do this:

<!--  HTML file -->
<ul>
  <li>Speaker</li>
  <li data-my-shop>Coke</li>
  <li>Cake</li>
  <li data-my-shop>Pepsi</li>
</ul>
 /* CSS file */

[data-my-shop] {
  color: red;
}

Preview

[attribute] selector preview

Notice the second and fourth list item that has the attribute data-my-shop got their text color changed to red.

2. [attribute=”value”] selector

The [attribute=”value”] selector is used to select all the matching elements based on the attribute name and exact attribute value specified. It is more explicit than the [attribute] selector because it searches for that attribute value.

Example of [attribute=”value”] selector

Using the same beverage example with a few things added, let’s style the data-my-shop attribute that’s equal to true.

<!--  HTML file -->
<ul>
  <li data-my-shop="false">Speaker</li>
  <li data-my-shop="true">Coke</li>
  <li data-my-shop="false">Cake</li>
  <li data-my-shop>Pepsi</li>
</ul>
/* CSS file */
[data-my-shop="true"] {
   color: red;
}

Preview

The example shows the use of [data-my-shop=”true”] selector, which checks for the attribute value “true”, and only the second list item met the condition. Notice the last list item had the attribute data-my-shop but without a value, and it doesn’t default as true.

If you need responsive and highly customizable components in your project without worrying about selectors, CSS, and all, check out Purecode.ai a repository of 10,000+ AI-generated custom components.

3. [attribute~=”value”] selector

The [attribute~=”value”] selector is used to select elements that match the specified value, which can be a whitespace-separated list of words, but one of which is exactly the specified value.

MDN defines the [attribute~=”value”] selector this way:

“[attr~=”value”]: Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value..”

To understand this selector, let’s break down its definition.

What does whitespace-separated list of words mean for the [attribute~=”value”] selector?

It simply means that the attribute’s value is expected to be a list of words separated by whitespace (e.g., “word1 word2 word3”)

What does “but one of which is exactly the specified value”?

It means that the specified value must match exactly one of the values in the whitespace-separated list of words.

Example of [attribute~=”value”] selector

To put it all together, let’s look at an example with code.

<-- HTML file -->
<div>
  <p data-tags="apple banana orange">Banana</p>
  <p data-tags="apple orange">Orange</p>
  <p data-tags="strawberry grape">Grape</p>
  <p data-tags="lemon mango banana">Lemon</p>
</div>

Here’s the CSS rule:

/* CSS file */
[data-tags~="banana"] {
  /* Styles for elements where "banana" is one of the words in the data-tag attribute value */
  color: yellowgreen;
}

In this example, the CSS rule will match the p elements that have the word banana as one of the values of the data-tags attribute whitespace-separated list. The specified style (yellowgreen text color) will be applied to these elements.

Preview

One thing to note is that the [attribute~=”value”] selector can also match a single value that was specified, so it doesn’t have to be used with only whitespace-separated list of words. For example

<-- HTML file --> 
<div>
    <p data-tags="banana">Banana</p>
    <p data-tags="apple orange">Orange</p>
    <p data-tags="strawberry grape">Grape</p>
    <p data-tags="banana">Lemon</p>
 </div>
/* CSS file */
[data-tags~="banana"] {
    color: yellowgreen;
 }

Preview

Notice, that the preview is still the same as when whitespace-separated list of words was used

4. [attribute|=”value”] selector

The [attribute|=”value”] selector is used to select elements with the specified attribute, whose value can be exactly the specified value or the specified value followed by a hyphen symbol (-).

Note that the value must consist of either a single word, like class=”todo”, or the word followed by a hyphen (-), for example, class=”todo-1″.

Example of [attribute|=”value”] selector

<-- HTML file --> 
<div>
  <p class="todo">Going for my daily exercises</p>
  <p class="todo-1">Learning the fundamentals of CSS</p>
  <p class="todo-2">Reading my school books, specifically English</p>
  <p class="todo-3">Doing my chores at home</p>
  <p class="done">Read my story book</p>
</div> 
/* CSS file */
[class|="todo"] {
  color: red;
}

In the code above, noticed that all the class name values that have todo as its specified attribute value got styled color red.

Preview

5. [attribute^=”value”] selector

The [attribute^=”value”] selector in CSS is used to select elements that have a specific attribute with a value that begins with the specified prefix value. This selector matches elements where the attribute value starts with the specified value.

Example of [attribute^=”value”] selector

<-- HTML file --> 
<a href="https://example.com/page1">Link 1</a>
<a href="https://example.com/page2">Link 2</a>
<a href="https://anotherdomain.com/page3">Link 3</a>
/* CSS file */
[href^="https://example.com"] {
  /* Styles for links with href starting with "https://example.com" */
  color: blue;
}

In this example, only the first two links will be styled because their href attributes start with “https://example.com.”

The [attribute^=”value”] selector is particularly useful when you want to apply styles to elements with attribute values that share a common prefix.

6. [attribute$=”value”] selector

The [attribute$=”value”] selector is used to select elements that have a specific attribute with a value that ends with the specified suffix value. This selector matches elements where the attribute value ends with the specified value.

Example of [attribute$=”value”] selector

<-- HTML file --> 
<a href="document1.pdf">Document 1</a>
<a href="document2.docx">Document 2</a>
<a href="document3.pdf">Document 3</a>
/* CSS file */
[href$=".pdf"] {
  /* Styles for links with href ending with ".pdf" */
  color: red;
}

In this case, the first and third links will be styled with a red color because their href attributes end with “.pdf.”

The [attribute$=”value”] selector is useful when you want to apply styles to elements with attribute values that share a common suffix.

7. [attribute*=”value”] selector

The [attribute*=”value”] selector is used to select elements that have a specific attribute with a value containing the specified substring value. This selector matches elements where the attribute value includes the specified value anywhere within it.

Example of [attribute*=”value”] selector

Consider a scenario where you want to style input elements whose placeholder attribute contains the substring “username”:

<-- HTML file --> 
<input type="text" placeholder="Enter your username">
<input type="password" placeholder="Password">
<input type="text" placeholder="Another username example">
/* CSS file */
[placeholder*="username"] {
  border: 1px solid #007bff;
}

In this case, the first and third input elements will be styled with a blue border because their placeholder attributes contain the substring “username.”

The [attribute*=”value”] selector is useful when you want to apply styles to elements with attribute values that include a specific substring, regardless of its position within the value.

Attribute Selector Sensitivity

In CSS, attribute selectors are case-sensitive by default. This means that when you use an attribute selector to target an element based on the value of its attribute, the matching is case-sensitive.

Case-Sensitive Attribute Selectors:

When you use an attribute selector like [attribute=”value”], it matches elements where the attribute has the exact value of “value”. This match is case-sensitive, meaning that uppercase and lowercase letters must match exactly.

/* Case-sensitive attribute selector */
[data-role="Admin"] {
  color: red;
}
<!-- This will be styled because the attribute value matches exactly -->
<div data-role="Admin">Administrator</div>

<!-- This will not be styled because the case does not match exactly -->
<div data-role="admin">Regular User</div>

Case-Insensitive Attribute Selectors:

If you need a case-insensitive attribute selector, you can use the i flag. For example, [attribute=”value” i] makes the match case-insensitive.

Example

/* Case-insensitive attribute selector */
[data-role="Admin" i] {
  color: red;
}

Now, both elements with data-role=”Admin” and data-role=”admin” will be styled because the case is ignored during the matching.

Combining Attribute Selectors

So far, we’ve seen how the different types of selectors can be used, but most times, you’d likely want to combine other selectors with the attribute selector, to make your CSS rule more specific to HTML element(s). Attribute selectors can be combined with other selectors like type, class, or id.

Example of Type selector combined with the Attribute Selector

The example below is from the [attribute*=”value”] selector example, but now we’ve added a type input, meaning it’ll only target inputs element that has the placeholder attribute, with the substring value as username.

input[placeholder*="username"] {
  /* Styles for input elements with placeholder containing "username" */
  border: 1px solid #007bff;
}

Example of Class selector combined with the Attribute Selector

Let’s say you want to style boxes differently based on both their class and the value of the data-status attribute. You can use a combination of class and attribute selectors:

<-- HTML file --> 
<div class="box" data-status="active">Active Box</div>
<div class="box" data-status="inactive">Inactive Box</div>
<div class="box" data-status="pending">Pending Box</div>
/* CSS file */
.box {
   padding: 30px;
}

/* Styles for active boxes with the "box" class and data-status="active" */
.box[data-status="active"] {
  background-color: green;
  color: white;
}

/* Styles for inactive boxes with the "box" class and data-status="inactive" */
.box[data-status="inactive"] {
  background-color: red;
  color: white;
}

/* Styles for pending boxes with the "box" class and data-status="pending" */
.box[data-status="pending"] {
  background-color: yellow;
  color: black;
}

In this example:

  • Boxes with the class “box” and data-status=”active” will have a green background and white text.

  • Boxes with the class “box” and data-status=”inactive” will have a red background and white text.

  • Boxes with the class “box” and data-status=”pending” will have a yellow background and black text.

Preview

 Class selector combined with the Attribute Selector preview

Example of ID selector combined with the Attribute Selector

Let’s say you want to style items differently based on both their ID and the value of the data-category attribute. You can use a combination of ID and attribute selectors:

<-- HTML file --> 
<div id="item1" data-category="fruit">Apple</div>
<div id="item2" data-category="vegetable">Carrot</div>
<div id="item3" data-category="fruit">Banana</div>
/* CSS file */
/* Styles for items with ID "item1" and data-category="fruit" */
#item1[data-category="fruit"] {
  color: red;
}

/* Styles for items with ID "item2" and data-category="vegetable" */
#item2[data-category="vegetable"] {
  color: green;
}

/* Styles for items with ID "item3" and data-category="fruit" */
#item3[data-category="fruit"] {
  color: orange;
}

In this example:

  • The item with the ID “item1” and data-category=”fruit” will have red text.

  • The item with the ID “item2” and data-category=”vegetable” will have green text.

  • The item with the ID “item3” and data-category=”fruit” will have orange text.

Example of Multiple attribute selectors

Yes, it’s possible to combine multiple attribute selectors for more specific rules targeting elements that satisfy multiple conditions.

<-- HTML file --> 
<input type="text" data-category="fruit" data-status="ripe">
<input type="text" data-category="vegetable" data-status="fresh">
<input type="text" data-category="fruit" data-status="ripe">
/* CSS file */
/* Styles for input elements with data-category="fruit" and data-status="ripe" */
input[data-category="fruit"][data-status="ripe"] {
  border: 2px solid green;
}

/* Styles for input elements with data-category="vegetable" and data-status="fresh" */
input[data-category="vegetable"][data-status="fresh"] {
  border: 2px solid orange;
}

In this example:

  • The first and third input elements will be styled with a green border because they satisfy the condition data-category=”fruit” and data-status=”ripe”.

  • The second input element will be styled with an orange border because it satisfies the condition data-category=”vegetable” and data-status=”fresh”.

Dynamic Styling

Dynamic styling with attribute selectors involves using pseudo-classes in combination with attribute selectors to create styles that respond to user interactions or specific states of elements. Here are examples of dynamic styling using attribute selectors:

Example 1: Styling links on hover:

This example dynamically changes the link color on hover based on the data-color attribute.

<-- HTML file --> 
<a href="#" data-color="blue">Blue Link</a>
<a href="#" data-color="green">Green Link</a>
/* CSS file */
a[data-color]:hover {
  color: attr(data-color);
}

Example 2: Highlighting checked checkboxes

This CSS rule dynamically highlights the label next to a checked checkbox.

<-- HTML file --> 
<input type="checkbox" id="checkbox1" checked>
<input type="checkbox" id="checkbox2">
/* CSS file */
input[type="checkbox"]:checked + label {
  background-color: yellow;
}

Example 3: Styling Placeholder text on focus

This example changes the color of the placeholder text when the input field is in focus.

<-- HTML file --> 
<input type="text" placeholder="Enter your name">
<input type="email" placeholder="Enter your email">
input[placeholder]:focus::placeholder {
  color: #999;
}

Example 4: Styling disabled buttons

<-- HTML file --> 
<button disabled>Disabled Button</button>
<button>Enabled Button</button>
/* CSS file */
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

This CSS rule dynamically styles disabled buttons, adjusting their opacity and cursor.

Performance Implications

Throughout our in-depth exploration of CSS attribute selectors, we’ve delved into their techniques and applications, uncovering their versatility in styling HTML elements based on attributes. However, as we harness the power of attribute selectors, it’s crucial to consider their performance implications, ensuring an optimal user experience.

Here are key considerations:

1. Selector Efficiency:

The efficiency of attribute selectors can vary. While simple attribute selectors are generally performant, more complex ones, especially those involving substring matching (*=), may incur a higher processing cost. Strive for specificity without unnecessary complexity.

2. Document Size and Complexity:

In larger documents with intricate structures, using overly broad or complex attribute selectors may lead to slower rendering times. Minimize selector complexity to enhance performance, particularly on extensive web pages.

3. Specificity and Selector Matching:

Highly specific selectors contribute to better performance. Aim for specificity to efficiently identify and style elements, reducing the computational overhead during selector matching.

4. Avoiding Universal Selectors:

The universal selector (*) can adversely impact performance, especially when used without constraints. Minimize its use to prevent unnecessary processing across all elements in the document.

To mitigate potential performance issues:

Prioritize Specificity:

Use more specific selectors to precisely target elements, reducing the need for extensive matching calculations.

Test and Optimize:

Utilize browser developer tools to measure the performance of your styles. Identify and optimize selectors that may cause bottlenecks.

Minimize Selector Complexity:

Simplify attribute selectors where possible, particularly in scenarios where performance is critical.

Consider CSS Preprocessors:

CSS preprocessors like Sass or Less can aid in organizing and optimizing styles, potentially reducing the complexity of selectors.

To better understand how to deal with performance issues that may arise with CSS attribute selectors or selectors in general, here is a guide to follow.

The truth about CSS selector performance


By balancing expressive styling with performance considerations, developers can effectively leverage CSS attribute selectors without compromising the speed and efficiency of their web pages.

Best Practices for CSS Attribute Selectors

Best PracticeExplanation
Be SpecificUse specific attribute selectors to avoid unintended styling conflicts.
Avoid OveruseLimit the use of universal selectors (*) and attribute selectors to prevent performance bottlenecks.
Optimize for PerformanceSimplify selectors for better performance, especially in large documents.
Consider SpecificityUnderstand and balance specificity when combining attribute selectors with other selectors.
Test Cross-Browser CompatibilityTest attribute selectors across various browsers to ensure consistent behavior.
Use Attribute Selectors with Pseudo-classesCombine attribute selectors with pseudo-classes for dynamic and interactive styling.
Use Descendant Selectors SparinglyAvoid excessively nested selectors, especially when using attribute selectors within descendant selectors.
Regularly Review and RefactorPeriodically review and refactor your CSS, especially attribute selectors, to maintain a scalable and efficient codebase.

To learn more about best practices when it comes to Attribute selector, read this extensive guide: Best Practices for CSS Selectors: Optimal Performance and Code Readability

Real-world Examples

In this section, we’ll build a simple task management application where attribute selectors play a key role in styling and user interaction. The task manager application has three fixed tasks, whose status can either be todo, in-progress, or completed. CSS attribute selectors are used to track the status of each tasks which can be toggled between statuses with the help of JavaScript.

Project: Task Manager

Video link for the project here

https://jomefavourite.github.io/Images/task-manager-purecode.mp4

HTML Structure

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>Task Manager</title>
</head>
<body>
  <div class="task-list">
    <div class="task" data-status="todo">
      <span class="status">Todo</span> Task 1
    </div>
    <div class="task" data-status="in-progress">
      <span class="status">In Progress</span> Task 2
    </div>
    <div class="task" data-status="completed">
      <span class="status">Completed</span> Task 3
    </div>
    <!-- Add more tasks as needed -->
  </div>

  <script src="app.js"></script>
</body>
</html>

CSS Style

/* style.css */

body {
  font-family: 'Arial', sans-serif;
  margin: 0;
  padding: 20px;
  background-color: #f0f0f0;
}

.task-list {
  display: flex;
}

.task {
  padding: 10px;
  margin: 10px;
  border: 1px solid #ccc;
  cursor: pointer;
}

.status {
  font-size: 12px;
}

/* Styling based on task status using attribute selectors */
.task[data-status="todo"] {
  background-color: #ffddcc;
}

.task[data-status="in-progress"] {
  background-color: #cceecc;
}

.task[data-status="completed"] {
  background-color: #ddd;
  text-decoration: line-through;
  color: #666;
}

/* Hover effect for all tasks */
.task:hover {
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
// app.js

document.addEventListener('DOMContentLoaded', function () {
  const tasks = document.querySelectorAll('.task');

  tasks.forEach(task => {
    task.addEventListener('click', function () {
      // Toggle task status on click
      const currentStatus = this.getAttribute('data-status');
      const newStatus = currentStatus === 'todo' ? 'in-progress' : 'completed';

      // Update the data-status attribute
      this.setAttribute('data-status', newStatus);

      // Update the displayed status on the UI
      const statusElement = this.querySelector('.status');
      statusElement.textContent = capitalizeFirstLetter(newStatus);
    });
  });

  // Helper function to capitalize the first letter of a string
  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }
});

Project Overview:

  • The HTML structure represents a simple task manager with tasks categorized by their status.

  • CSS attribute selectors are extensively used to style tasks based on their status (todo, in-progress, completed).

  • The JavaScript code adds interactivity by allowing users to toggle task status on click.

Summary of CSS Attribute Selector

We’ve gone over the 7 different CSS attribute selectors, plus the case-insensitive attribute selector, combining attributes with other selectors, best practices to follow, and a real-world use case when it comes to using the attribute selector. Let’s view the summary of all the selectors in a tabular view, showing the description of each attribute selector we have in CSS.

Attribute SelectorDescription
1[attribute]Selects elements that have the specified attribute, regardless of its value.
2[attribute=”value”]Selects elements where the attribute value is an exact match to the specified value.
3`[attribute~=”value”]`Selects elements where the specified attribute contains a whitespace-separated list of words, and one of those words is an exact match to the specified value.
4[attribute|=”value”]Selects elements where the specified attribute’s value is an exact match to the specified value or begins with the specified value followed by a hyphen.
5[attribute^=”value”]Selects elements where the attribute value starts with the specified value.
6[attribute$=”value”]Selects elements where the attribute value ends with the specified value.
7[attribute*=”value”]Selects elements where the attribute value contains the specified substring anywhere within it.
8[attribute=”value” i]Selects elements based on the case-insensitive matching of the attribute value.

Conclusion

In concluding our exploration of CSS attribute selectors, we’ve unveiled a robust toolset for precise element styling based on attributes. From fundamental syntax to advanced techniques, these selectors offer a flexible approach to web design.

We’ve demonstrated how attribute selectors can dynamically respond to user interactions, enhancing the user experience. By combining these selectors with pseudo-classes, developers can create engaging and responsive designs.

As we navigate practical applications and considerations like accessibility and performance, it’s clear that CSS attribute selectors play a vital role in modern web development. Mastering these selectors empowers developers to craft efficient, visually appealing, and user-friendly interfaces. In a rapidly evolving web landscape, the skillful use of attribute selectors remains a cornerstone for effective front-end development.

Further Reading

To learn more about CSS attribute selectors, you can go through these guides:

If you enjoyed reading this article, consider checking out other great pieces from our blog.

One last thing, before we finally conclude. If you’re tired of creating the same UI components over and over, check out Purecode.ai today, cause we provide you with over 1000+ components that are AI-generated, styled with your favourite CSS toolings and UI Library, TailwindCSS, and MUI.

Favourite Jome

Favourite Jome