CSS Attribute Selectors

Through CSS attribute selectors, we can apply style based on presence of a particular attribute or its value.

Square brackets are used after element name in CSS to notify that we are targeting attributes.

Element[attribute]{
	property
}

CSS [attribute] Selector

This selector will be targeted to every element which has this attribute.

Input:-

Index.html
	
<body> 
	  <a href=”#”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title] {
   color: aqua;
} 

Output:-


CSS [attribute=”value”] Selector

We can use the = operator to make an attribute selector matches any element whose attribute value is exactly equal to the given value.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title=”Click me”] {
   color: aqua;
} 

Output:-


CSS [attribute~=”value”] Selector

We can use the ~= operator to make an attribute selector matches any element whose attribute value is a list of space-separated values, one of which is exactly equal to the specified value.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title~=”Click”] {
   color: aqua;
} 

Output:-


CSS [attribute|=”value”] Selector

We can use the |= operator to make an attribute selector matches any element whose attribute has a hyphen-separated list of values beginning with the specified value.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click-Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title|=”Click”] {
   color: aqua;
} 

Output:-


CSS [attribute^=”value”] Selector

We can use the ^= operator to make an attribute selector matches any element whose attribute value starts with a specified value. It does not have to be matched as a whole word.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click-Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title^=”Cli”] {
   color: aqua;
} 

Output:-


CSS [attribute$=”value”] Selector

We can use the $= operator to select all elements whose attribute value ends with a specified value. It does not have to be matched as a whole word.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click-Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
</body>

Style.css
a[title$=”nk1”] {
   color: aqua;
} 

Output:-


CSS [attribute*=”value”] Selector

We can use the *= operator to make an attribute selector matches all elements whose attribute value contains a specified value.

For eg – when I pass click as a value in * attribute, it will target click, click me, click-me. Every value with hypen or with space.

Input:-

Index.html
	
<body> 
	  <a href=”#” title=”Click-Link1”>Link 1</a>
	  <a href=”#” title=”Click me”>Link 2</a>
   <a href=”#” title=”Click”>Link 3</a>
</body>

Style.css
a[title*=”Click”] {
   color: aqua;
} 

Output:-