Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Is it possible to use IMG Alt attribute for styling?

Tags:

html

css

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?

like image 391
StandardNerd Avatar asked Sep 27 '16 07:09

StandardNerd


2 Answers

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
}
like image 106
derdida Avatar answered Nov 15 '22 08:11

derdida


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.

like image 45
thepio Avatar answered Nov 15 '22 08:11

thepio