CSS: Can I use the IMG Alt attribute for styling?

This is something that I have not had to deal with before.

To serve an outdated system, I cannot directly edit HTML to add a CSS class to the image tag.

But is it possible to use the style of the alt tag for styling?

<img class="thumbnail" src="/H14547_front_anthrazit.jpg" alt="H14547 front anthrazit">

I want to use the text "front" inside the alt attribute for the image style:

img[alt="front"] { padding: .2rem }

Can I use the IMG Alt attribute for styling? And how exactly?

+4
source share
3 answers

Using:

The value contains:

img[alt*="front"] {
   padding: .2rem
}

The value is in a list, separated by a space : (Thus, it works with "front", but not with "frontpage")

img[alt~="front"] {
   padding: .2rem
}

The value begins with:

img[alt^="front"] {
   padding: .2rem
}

( alt )

a[href$="front"] {
   padding: .2rem
}
+8

, . ~=, "if contains".

img[alt~="front"] {
  padding: .2rem;
  border: 3px solid red;
}
<img class="thumbnail" src="http://www.texaswildflowerpictures.com/images/flower_pink.png" alt="front">
<img class="thumbnail" src="http://www.texaswildflowerpictures.com/images/flower_pink.png" alt="H14547 front anthrazit">
<img class="thumbnail" src="http://www.texaswildflowerpictures.com/images/flower_pink.png" alt="H14547 anthrazit">
Hide result

. , alt="this is the front", alt="this is the frontpage". , . , *=, derdida.

+4

It should be possible, and it is. In your case, you should write something like this.

img[alt*="front"] { 
   padding: .2rem 
}

It works with every attribute. You can even use this approach to work with / substitute classes or identifiers. This should not be a problem for modern browsers. for instance

#one {
color:#f00;  
}

[id="one"] {
background-color:#0099ff;  
}

.oneofus {
padding:20px;  
}

[class="oneofyou"] {
background-color:#ff0;  
}
<div id="one" class="oneofus">Text</div>
<p>Something something</p>
<div id="one" class="oneofyou">Another Text</div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1655929/


All Articles