Attribute Selectors in CSS

css attribute selectors guide
10 November 2024

In the world of web design, CSS is one of the essential and practical tools that allows web designers to control the appearance of web pages. One of the powerful features of CSS is the attribute selectors, which gives you the ability to apply specific styles to HTML elements based on their attributes. This feature is particularly useful when you want to apply a specific style to elements identified by specific attributes, without needing to rely on a specific class or ID.

Attribute selectors have different types that each serve a specific purpose. For example, you can select elements based on the presence of a specific attribute, the value of that attribute, or even part of that value. This flexibility allows you to have finer control over the styling of elements that possess specific attributes.

Next, we will examine several common types of attribute selectors. Basic attribute selectors include [attr] for selecting all elements that have a specified attribute and [attr="value"] for selecting elements with a specific attribute having a defined value.

You can also use specialized attribute selectors like [attr^="value"] to select elements whose attribute value starts with a specific value, [attr*="value"] for finding elements whose attribute value contains a specific value, and [attr$="value"] for selecting elements whose attribute value ends with a specific value.

Example Code and Practical Use


<style>
  /* Select all elements with the title attribute */
  [title] {
    color: blue;
  }

  /* Select input elements of type text */
  input[type="text"] {
    border: 1px solid #ccc;
  }

  /* Select links that start with https */
  a[href^="https"] {
    color: green;
  }

  /* Select links that contain 'example' in the href */
  a[href*="example"] {
    font-weight: bold;
  }

  /* Select images with png format */
  img[src$=".png"] {
    border: 2px solid red;
  }
</style>
<input type="text" title="Sample Input"/>
<a href="https://www.example.com">Example Link</a>
<img src="image.png" alt="PNG Image"/>

Line by Line Code Explanation:

[title]
This line selects all HTML elements that possess the title attribute and sets their text color to blue.

input[type="text"]
This line targets all input elements of type text, applying a subtle border style.

a[href^="https"]
This line selects all links (tag a) that have an href attribute beginning with https, coloring them green.

a[href*="example"]
This line selects links containing the keyword example in their href, making them bold for emphasis.

img[src$=".png"]
This line selects all images in png format, applying a red border around them.

FAQ

?

How can I use attribute selectors in CSS?

?

When is it appropriate to use attribute selectors?

?

What are the advantages of using attribute selectors compared to classes?