HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

CSS Attribute Selectors

CSS attribute selectors are a powerful feature of CSS that allow you to select HTML elements based on the presence of specific attributes or their attribute values. They provide a way to style elements based on their attributes, which can be particularly useful for targeting elements with certain characteristics or for enhancing the styling of elements dynamically. There are several types of attribute selectors:

Existence Attribute Selector ([attribute]):

Selects elements that have the specified attribute, regardless of its value.

Example

a[target] {
    color: red;
}  
You can click on above box to edit the code and run again.

Output

Equality Attribute Selector ([attribute=value]):

Selects elements with the specified attribute and value.

Example

input[type="text"] {
    border: 1px solid #ccc;
}  
You can click on above box to edit the code and run again.

Output

Prefix Attribute Selector ([attribute^=value]):

Selects elements where the attribute value begins with a specified value.

Example

[class^="btn-"] {
    background-color: yellow;
} 
You can click on above box to edit the code and run again.

Output

Suffix Attribute Selector ([attribute$=value]):

Selects elements where the attribute value ends with a specified value.

Example

a[href$=".pdf"] {
    color: blue;
}
You can click on above box to edit the code and run again.

Output

Substring Attribute Selector ([attribute*=value]):

Selects elements where the attribute value contains the specified value anywhere within it.

Example

img[alt*="logo"] {
    width: 100px;
} 
You can click on above box to edit the code and run again.

Output

Attribute with a Certain Value ([attribute~=value]):

Selects elements where the attribute value is a whitespace-separated list of words, one of which matches the specified value.

Example

[class~="important"] {
    font-weight: bold;
} 
You can click on above box to edit the code and run again.

Output


These selectors provide a way to target elements in your HTML based on their attributes and their values, offering greater flexibility and control in styling and targeting specific elements.