CSS [attribute~=value] Selector

Description

The CSS [attribute~="value"] selector is used to select elements with an attribute value containing a specified word. The word can be anywhere in the attribute value, and it can be followed by other words.

For example, the following selector will select all elements with a title attribute containing the word "flower":

[title~="flower"] {
  color: red;
}

This will select the following elements:

<div title="flower">This is a flower.</div>
<div title="summer flower">This is a summer flower.</div>
<div title="flower new">This is a new flower.</div>

However, it will not select the following elements:

<div title="my-flower">This is my flower.</div>
<div title="flowers">This is a bunch of flowers.</div>

The [attribute~="value"] selector is often used to style elements based on their content. For example, you could use it to style all links that contain the word "external" in their href attribute, or to style all images that contain the word "product" in their src attribute.

Here is another example:

[href~="external"] {
  color: blue;
}

[src~="product"] {
  border: 1px solid black;
}

This will style all links with href attributes containing the word "external" to be blue, and all images with src attributes containing the word "product" to have a black border.

The [attribute~="value"] selector is a powerful tool for styling elements based on their content. It can be used to create more specific and dynamic styles.

Syntax

[attribute~=value] {
    css declarations;
}

Example

a[title~="America"] {
   color: #3366ff;
   background: #ffff99;
}

Give it a Try

Click the button below to experiment with this selector.

Give it a Try!

Browser Support

The following table will show you the current browser support for the CSS [attribute~=value] selector.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes