Attribute Selectors in CSS


The CSS Attribute Selector selects elements based on their attribute presence or value.

  • Selects elements with specific attributes such as href, type, target, title, alt, id, class, and more.
  • Enables precise and flexible styling.

Syntax

element[attribute] {
  property: value;
} 
  • Selects elements that have the specified attribute

css-attribute-selector


Types of Attribute Selectors

Selector Description Example
[attr] Has attribute input[required]
[attr="value"] Attribute equals value a[target="_blank"]
[attr~="value"] Attribute contains word (space-separated) [title~="flower"]
[attr^="value"] Value starts with a[href^="https"]
[attr$="value"] Value ends with img[src$=".png"]
[attr*="value"] Value contains a[href*="example"]

Example

[attr] — Has Attribute

input[required] {
  border: 2px solid red;
} 

All input fields with the required attribute will have a red border.

 


[attr="value"] — Exact Match

a[target="_blank"] {
  color: green;
}

Styles only links that open in a new tab/window (target="_blank").

 


[attr~="value"] — Contains Word

[title~="flower"] {
  background-color: yellow;
}

Matches elements where the title attribute contains the word "flower".

 


[attr|="value"] — Starts With Value or Value-

[lang|="en"] {
  color: blue;
}

Matches elements with lang="en" or lang="en-US".

 


Example

<!DOCTYPE html>
<html>
<head>
  <style>
    a[target="_blank"] {
      color: green;
    }

    input[required] {
      border: 2px solid red;
    }

    img[src$=".png"] {
      border: 2px solid blue;
    }
  </style>
</head>
<body>

<a href="https://example.com" target="_blank">External Link</a>
<a href="https://example.com">Normal Link</a>

<br><br>

<input type="text" required placeholder="Required Field">
<input type="text" placeholder="Optional Field">

<br><br>

<img src="image.png" alt="A PNG image">
<img src="photo.jpg" alt="A JPG image">

</body>
</html> 

Advantages

  • Powerful for targeting elements without adding extra classes or IDs.
  • Great for form styling, link management, and accessibility features.



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.