Reputation: 499
I'm putting together some Responsive CSS for a website I'm building and I'm curious if I can use CSS to force images to render as alt text instead of images. We are displaying the logos of cosponsors but because of their variable size it's hard to fit them confidently into the responsive design. For that reason we'd like to store the company name as alt text and render that instead. Of course we could place the name in a separate element and toggle the visibility using CSS but using alt text seems DRYer.
Upvotes: 7
Views: 9840
Reputation: 31
(answered for any others looking for a solution)
Important aside: Remember the purpose of alt: to display meaningful ALTERNATIVE information (if the image doesn't load). - so any implementation should not break that... (bad for accessibility & SEO).
That said... If the image doesn't load, the alt will be displayed. So (untested) but you could try messing up the src attribute by javascript... this should cause the browser to display the alt since the image wont load. - you might find this approach along with lazyload useful.
Also to note: a broken img doesn't behave like an image, so you can apply a img:before css rule (and use content: attr(alt) )
Upvotes: 0
Reputation: 48476
You could store that in a data-attribute rather than the alt text, and then do something like this:
<span class='responsive' data-alt='foo'>
<img src='http://www.ponyfoo.com/img/thumbnail.png' alt='' />
</span>
@media only screen and (max-width: 300px) {
.responsive:before {
content: attr(data-alt);
}
.responsive img {
display: none;
}
}
The reason you can't do this just with CSS and an img
tag is that img
tags is because they are replaced elements, which means pseudo doesn't work with them, and therefore, using :before
doesn't work with them.
Another approach, taking this into account would be the following:
<span class='responsive'>foo</span>
.responsive {
background-image: url('http://www.ponyfoo.com/img/thumbnail.png');
text-indent: -9999em;
overflow: hidden;
width: 180px;
height: 180px;
display: block;
}
@media only screen and (max-width: 300px) {
.responsive {
background-image: none;
text-indent: initial;
overflow: initial;
}
}
If you ask me, I like the second approach a lot more.
Upvotes: 8
Reputation: 499
Went with:
<div class="cobranding">
<span>Brought to you by</span>
<span class="sponsor">Joe Shmoe Inc.</span>
<img src="img/graphics/joe_shmoe_logo.jpg">
</div>
Using CSS to toggle the visibility of the img or the "sponsor" based on responsive breakpoints.
Both of Nico's approaches look good. The only hiccup is that these cosponsor logos are going to be added via a CMS so I want to steer away from any solution involving case-by-case CSS (:before or background-image). For the sake of time I went ahead with the two element strategy above.
Upvotes: 0