How to select elements with a specified attribute and value with CSS

The CSS [attribute="value"] selector is used to select elements that have a specific attribute with an exact matching value. This attribute selector is particularly useful for targeting elements based on their HTML attributes like rel, type, class, or custom data attributes.

Syntax

element[attribute="value"] {
    /* CSS properties */
}

Example: Selecting Links with Specific rel Attribute

The following example demonstrates how to select and style anchor elements that have a rel attribute with the value "nofollow" −

<!DOCTYPE html>
<html>
<head>
    <style>
        a[rel="nofollow"] {
            border: 3px solid blue;
            padding: 5px;
            text-decoration: none;
            background-color: #f0f0f0;
        }
        
        a[rel="noreferrer"] {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <a href="https://example.com/business-model" rel="nofollow">Business Model Guide</a>
    <br><br>
    <a href="https://example.com/share-market" rel="noreferrer">Share Market Guide</a>
    <br><br>
    <a href="https://example.com/general-link">General Link</a>
</body>
</html>
The first link "Business Model Guide" appears with a blue border, padding, and gray background due to its rel="nofollow" attribute. The second link "Share Market Guide" appears in red bold text due to its rel="noreferrer" attribute. The third link appears with default styling as it has no rel attribute.

Example: Selecting Input Elements by Type

You can also use this selector to target form elements based on their type attribute −

<!DOCTYPE html>
<html>
<head>
    <style>
        input[type="email"] {
            background-color: #e6f3ff;
            border: 2px solid #007bff;
            padding: 8px;
        }
        
        input[type="password"] {
            background-color: #fff3cd;
            border: 2px solid #ffc107;
            padding: 8px;
        }
    </style>
</head>
<body>
    <form>
        <label>Email: <input type="email" placeholder="Enter email"></label>
        <br><br>
        <label>Password: <input type="password" placeholder="Enter password"></label>
        <br><br>
        <label>Text: <input type="text" placeholder="Enter text"></label>
    </form>
</body>
</html>
The email input field appears with a light blue background and blue border. The password input field appears with a light yellow background and yellow border. The text input field appears with default styling as it doesn't match any specific attribute selector.

Conclusion

The [attribute="value"] selector provides precise control for styling elements based on their exact attribute values. It's particularly useful for form elements, links, and any HTML elements with specific attributes you need to target.

Updated on: 2026-03-15T12:36:28+05:30

276 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements