7

This is one I have not had to tackle before.

For maintenance of a legacy System I can't edit HTML directly to add a CSS class to an image tag.

But is it possible to use image tag's alt text 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 to style the image like:

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

Is it possible to use IMG Alt attribute for styling? And how exactly?

3 Answers 3

16

Use:

Value contains:

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

Value is in a space separated list: (So it works with "front", but not with "frontpage")

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

Value starts with:

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

Value ends with (so all alt tags the end with front)

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

Yes you can. Use the ~= selector to choose "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">

Note: This works with only a whitespace separated word like alt="this is the front" but will not work with alt="this is the frontpage". But this is the way I imagine it should be in your case. If it should work in the latter case use the *= selector as pointed at first by derdida.

2
  • It might be worth mentioning that this only works if the string "front" is seperated by a whitespace from anything else in the attribute value.
    – Andii
    Commented Sep 27, 2016 at 7:43
  • That's true. The way I imagine this is that it should be so. Let's say there's a image with alt="this is the frontpage" - I would not like it to be chosen by the CSS declaration. Maybe that's just me :P Thank you for the comment and notifying this though :)
    – thepio
    Commented Sep 27, 2016 at 7:46
0

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 ids. It shouldn't be problem with modern browsers. For example

#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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.