How to select elements with a specified attribute with CSS

CSS attribute selectors allow you to target HTML elements that contain a specific attribute, regardless of the attribute's value. The [attribute] selector is used to select all elements that have the specified attribute present.

Syntax

[attribute] {
    /* styles */
}

Example: Selecting Images with Alt Attribute

The following example applies an orange border to all <img> elements that have an alt attribute −

<!DOCTYPE html>
<html>
<head>
<style>
    img[alt] {
        border: 3px solid orange;
        margin: 10px;
    }
    
    img {
        display: inline-block;
        margin: 10px;
    }
</style>
</head>
<body>
    <h3>Image without alt attribute:</h3>
    <img src="/images/logo.png" height="100" width="100">
    
    <h3>Image with alt attribute:</h3>
    <img src="/images/logo.png" height="100" width="100" alt="TutorialsPoint Logo">
</body>
</html>
Two images are displayed. The first image appears without any border. The second image has an orange border around it because it contains the alt attribute.

Example: Selecting Links with Target Attribute

This example demonstrates how to style links that open in a new window or tab using the target attribute −

<!DOCTYPE html>
<html>
<head>
<style>
    a[target] {
        background-color: yellow;
        padding: 5px;
        text-decoration: none;
        border-radius: 3px;
    }
    
    a {
        display: inline-block;
        margin: 10px;
        color: blue;
    }
</style>
</head>
<body>
    <p>Regular link: <a href="#">Internal Link</a></p>
    <p>External link: <a href="#" target="_blank">External Link</a></p>
</body>
</html>
Two links are displayed. The first link appears as a normal blue link. The second link has a yellow background and rounded corners because it contains the target attribute.

Conclusion

The CSS [attribute] selector is a powerful tool for targeting elements based on the presence of specific attributes. This allows for more semantic and accessible styling based on HTML structure rather than relying solely on classes or IDs.

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

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements