Typically, you style an image using its id, class attributes or tag name but in this article, you will learn how to style an image using its alt attribute.
<style>
img[alt="logo"]{
border:2px solid red;
}
</style>
<img alt="logo" src="https://app.3schools.in/logo.png">
Try it Yourself »
Using the attribute selector (eg. img[alt="logo"]) in css, you can style all the images that contain logo in the alt attributes.
Example 2 : style images that have alt attribute.
In the second example, I want to style images that have alt attributes (whatever the alt value is).
For example, I have three images. The first and second images have the Alt attribute but the third image has no Alt attribute. You can try to run the following code.
<style>
img[alt]{
border:2px solid red;
}
</style>
<img alt="logo" src="https://app.3schools.in/logo.png">
<img alt="3schools" src="https://app.3schools.in/logo.png">
<img src="https://app.3schools.in/logo.png">
Try it Yourself »
Example 3 : img[alt~=""] selector.
The img[alt~="logo"] selector select the image that contains the logo in the alt attribute.
<style>
img[alt~="logo"]{
border:2px solid gold;
}
</style>
<img alt="logo" src="https://app.3schools.in/logo.png">
<img alt="our official logo" src="https://app.3schools.in/logo.png">
<img alt="3schoolslogo" src="https://app.3schools.in/logo.png">
Try it Yourself »
Css img[alt*="logo"] selector
Basically, the img[alt*="logo"] selector select the image that contains the logo in the alt attribute even the alt text is alt="our official-logo".
<style>
img[alt*="logo"]{
border:2px solid gold;
}
</style>
<img alt="logo" src="https://app.3schools.in/logo.png">
<img alt="our official logo" src="https://app.3schools.in/logo.png">
<img alt="3schoolslogo" src="https://app.3schools.in/logo.png">
Try it Yourself »
img[alt^="logo"] and img[alt$="logo"] selector.
<style>
img[altalt^="logo"]{
border:2px solid gold;
}
</style>
<img alt="logo is" src="https://app.3schools.in/logo.png">
<img alt="our official logo" src="https://app.3schools.in/logo.png">
<img alt="3schoolslogo" src="https://app.3schools.in/logo.png">
Try it Yourself »
<style>
img[alt$="logo"]{
border:2px solid gold;
}
</style>
<img alt="logo" src="https://app.3schools.in/logo.png">
<img alt="our official logo" src="https://app.3schools.in/logo.png">
<img alt="3schoolslogo" src="https://app.3schools.in/logo.png">
Try it Yourself »
Comments (2)
How to style an image using its alt attribute
img[alt*="logo"] {
border: 2px solid gold;
}
But now all my logo images are getting this gold border, even the ones with alt="our official logo" and alt="3schoolslogo".
If you want EXACT MATCH, use the equals sign:
img[alt="logo"] {
}
If you wanted the alt text to START WITH "logo" (like alt="logo_v2"), you’d use the caret ^:
img[alt^="logo"] {
}