How to apply Alt and title to background image?? [duplicate] - css

This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute.
There is no CSS property like this as far as I know, so what is the best way to do this please?

Background images sure can present data! In fact, this is often recommended where presenting visual icons is more compact and user-friendly than an equivalent list of text blurbs. Any use of image sprites can benefit from this approach.
It is quite common for hotel listings icons to display amenities. Imagine a page which listed 50 hotel and each hotel had 10 amenities. A CSS Sprite would be perfect for this sort of thing -- better user experience because it's faster. But how do you implement ALT tags for these images? Example site.
The answer is that they don't use alt text at all, but instead use the title attribute on the containing div.
HTML
<div class="hotwire-fitness" title="Fitness Centre"></div>
CSS
.hotwire-fitness {
float: left;
margin-right: 5px;
background: url(/prostyle/images/new_amenities.png) -71px 0;
width: 21px;
height: 21px;
}
According to the W3C (see links above), the title attribute serves much of the same purpose as the alt attribute
Title
Values of the title attribute may be rendered by user agents in a variety of ways. For instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). Audio user agents may speak the title information in a similar context. For example, setting the attribute on a link allows user agents (visual and non-visual) to tell users about the nature of the linked resource:
alt
The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.
A text equivalent brings the following benefits to your website and its visitors in the following common situations:
nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

In this Yahoo Developer Network (archived link) article it is suggested that if you absolutely must use a background-image instead of img element and alt attribute, use ARIA attributes as follows:
<div role="img" aria-label="adorable puppy playing on the grass">
...
</div>
The use case in the article describes how Flickr chose to use background images because performance was greatly improved on mobile devices.

I think you should read this post by Christian Heilmann. He explains that background images are ONLY for aesthetics and should not be used to present data, and are therefore exempt from the rule that every image should have alternate-text.
Excerpt (emphasis mine):
CSS background images which are by definition only of aesthetic value
– not visual content of the document itself. If you need to put an
image in the page that has meaning then use an IMG element and give it
an alternative text in the alt attribute.
I agree with him.

As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.
The real question is why you need to add the alt attribute to all background images for the site? Based on this answer, it will help you determine which route to take in your approach.
Visual/Textual: If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.
Screen Readers: The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context." However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.
SEO/Search Engines: Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: https://www.searchenginejournal.com/how-to-use-link-title-attribute-correctly/. So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.

The general belief is that you shouldn't be using background images for things with meaningful semantic value so there isn't really a proper way to store alt data with those images. The important question is what are you going to be doing with that alt data? Do you want it to display if the images don't load? Do you need it for some programmatic function on the page? You could store the data arbitrarily using made up css properties that have no meaning (might cause errors?) OR by adding in hidden images that have the image and the alt tag, and then when you need a background images alt you can compare the image paths and then handle the data however you want using some custom script to simulate what you need. There's no way I know of to make the browser automatically handle some sort of alt attribute for background images though.

This article from W3C tells you what they think you should do
https://www.w3.org/WAI/GL/wiki/ARIATechnique_usingImgRole_with_aria-label_forCSS-backgroundImage
and has examples here
http://mars.dequecloud.com/demo/ImgRole.htm
among which
<a href="http://www.facebook.com">
<span class="fb_logo" role="img" aria-label="Connect via Facebook">
</span>
</a>
Still, if, like in the above example, the element containing the background image is just an empty container, I personally prefer to put the text in there and hide it using CSS; right where you show the image instead:
<a href="http://www.facebook.com"><span class="fb_logo">
Connect via Facebook
</span></a>
.fb_logo {
height: 37px; width: 37px;
background-image: url('../gfx/logo-facebook.svg');
color:transparent; overflow:hidden; /* hide the text */
}

The classical way to achieve this is to put the text into the div and use an image replacement technique.
<div class"ir background-image">Your alt text</div>
with background-image beeing the class where you assign the background image and ir could be HTML5boilerplates image replacement class, below:
/* ==========================================================================
Helper classes
========================================================================== */
/*
* Image replacement
*/
.ir {
background-color: transparent;
border: 0;
overflow: hidden;
/* IE 6/7 fallback */
*text-indent: -9999px;
}
.ir:before {
content: "";
display: block;
width: 0;
height: 150%;
}

Here's my solution for Immediate fix:
Once the background image is removed the alt text will be visible from Img tag.
.alt-image {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
.background-image{
background:url("https://www.w3schools.com/images/picture.jpg") no-repeat;
width:100%;
height:500px;
position:relative;
}
<div role="img" aria-label="place alt text here" title="place alt text here" class="background-image">
<img src="" alt="place alt text here" class="alt-image"/>
</div>

Here's my solution to this type of problem:
Create a new class in CSS and position off screen. Then put your alt text in HTML right before the property that calls your background image. Can be any tag, H1, H2, p, etc.
CSS
<style type="text/css">
.offleft {
margin-left: -9000px;
position: absolute;
}
</style>
HTML
<h1 class="offleft">put your alt text here</h1>
<div class or id that calls your bg image> </div>

It''s not clear to me what you want.
If you want a CSS property to render the alt attribute value, then perhaps you're looking for the CSS attribute function for example:
IMG:before { content: attr(alt) }
If you want to put the alt attribute on a background image, then ... that's odd because the alt attribute is an HTML attribute whereas the background image is a CSS property. If you want to use the HTML alt attribute then I think you'd need a corresponding HTML element to put it in.
Why do you "need to use alt tags on background images": is this for a semantic reason or for some visual-effect reason (and if so, then what effect or what reason)?

You can achieve this by putting the alt tag in the div were your image will appear.
Example:
<div id="yourImage" alt="nameOfImage"></div>

Related

Print css, only load images at print time

I'm currently developing a complex print style sheet which is in some ways different from the HTML currently displayed on screen. I've hit a hurdle with a balance between performance and achieving the desired layout.
Basically there is a gallery of images which are loaded via javascript on the fly. Images are built dynamically via JS and output to the DOM on each request for the next image.
My problem lies in that I need to build this for printing purposes. I think I'm left with a scenario where I will have to build additional html on the page just for the print page to look correct; that isn't so much of a problem, except the images are rather big, and even using "display:none" and media print { display:block; } won't prevent the images from being downloaded on desktop devices behind the scenes by the browser. In essence I need them to stay dormont on screens, and come to life using print styles.
I had considered using the css background-image property - which I believe doesn't cause the image to load in the browser, however background image doesn't seem to reliably print across different browsers.
I've also tried using onbeforeprint javascript, but again, this is mess of browser inconsistency.
Can anyone suggest any sort of solution for this? at the moment it seems like I'm going to have to suck up the additional overhead of all the images to achieve reliable results.
If background images are an option, you could prevent the download of those when setting the parent element of the image container to display: none
Example HTML:
<div class="invisible">
<div class="img-container">
</div>
</div>
Related CSS:
.invisible {
display: none;
}
.img-container {
background: url(img.xyz);
}
#media print {
.invisible {
display: block;
}
}
Apart from that a similar question had been asked: Prevent images from loading
May be that will help you, if background images are definitely NOT an option.

PHP: Add hover effect to image

I am working on a PHP file. I'm working on the menu bar, the menu bar contains all the image buttons, if someone hovers on one of the buttons I want them to change image(color). Could someone help me out with this?
$globalsettings = array(
'src' => $sImageURL.'global1.png',
'alt' => $clang->gT("Global participant settings"),
'title' => $clang->gT("Global participant settings"),
'style' => 'margin-left:5px',
'style' => 'margin-right:1px'
);
You can create hover effects using CSS (cascading stylesheets). Your CSS must be in an external stylesheet or embedded style element.
I'm using BUTTON that will style all <button> elements, but you can replace it with whatever element you want to style, such as an <img> with IMG (lowercase or uppercase).
BUTTON {
background: url(my_bg.png);
}
BUTTON:hover {
background: url(my_hover_bg.png);
}
If you don't know how to use stylesheets, just insert embedded styling into the <head> of your HTML document.
<style type="text/css">
/* Place CSS here */
</style>
If you want you can take it a step further and use CSS sprites (like old videos games used to do it). CSS sprites are a collection of images in one single image, and you simply change the position of the location of the background, and it creates the effect. You can achieve this like this:
#myelement {
background: url(my_bg.png) -0 -0;
}
#myelement:hover {
background: url(my_bg.png) -0 -100px;
}
There are also old school ways of hover effects but they're like Frontpage-era, so I don't recommend using them. CSS hover effects is the standard of today.
You're trying to solve 2 problems in one step. You need to get the images to display and then swap between them on hover.
You can't dynamically edit a button in JS (ok, you could with canvases and html 5 but it's non-trivial). So, you need to use CSS (or possibly JS) to to swap between 2 images.
Where those images come from is up to you - you can either pre-generate them which is a little work up front but easy to implement and no PHP required. This would be the preferred option if there's only one or two variations in colour.
Alternatively, you can have a PHP script which generates the images on-the-fly (and ideally caches them to save recomputing them later). This allows for infinite variation but requires more overhead on the server. This approach is commonly used to generate thumbnails as the source image isn't known in advance
Note that PHP has no control over when each image is displayed - it simply provides images to your CSS/JS in exactly the same way as a webserver would serve a static image.
If you want to edit an image in PHP, you need to look at the GD+ library
You can use css to do this quite easily by using the content: selector.
for example, your markup might look like this:
<div class="link" id="link1">
<img />
</div>
and the css would be something like:
#link1 a img{
content:url("http://www.maxxpotential.com/stephen2/wp-content/uploads/2013/03/Images-from-Deep-in-the-Woods-by-Astrid-Yskout-4.jpg");
}
#link1:hover a img{
content:url("http://blogs.mathworks.com/pick/files/zebrainpastelfield.png");
}
by using the selectors you assign in your script, you should find it pretty easy to amend this to suit your needs.
here is a working fiddle demonstrating this http://jsfiddle.net/pWYtu/1
You can use sprite image and onhover change position.
also you will get benefit of performance.

CSS Style Element if it does not contain another specific type of Element

My CSS includes the following:
#mainbody a[href ^='http'] {
background:transparent url('/images/icons/external.svg') no-repeat top right;
padding-right: 12px;
}
This places an "external" icon next to links that start with "http" (all internal site links are relative). Works perfectly except if I link an Image, it also get this icon.
For example: <a href='http://example.com'><img src='whatever.jpg'/></a> would also get the "external" icon next to the image. I can live with this if necessary, but would like to eliminate it.
This must be implement in CSS (no JS); must not require any special IDs, Classes, styling in the html for the image or anchor around the image. Is this possible?
It's case sensitive. Just use all capped HTTP: for image links.
You can either:-
Only use relative links for images
link to a naked domain for images (e.g. http://domain.com) and fix
the external link filter to www. rather than http.
No CSS required - you basically need to use a less common filter.

Put title/alt attributes into CSS :after { content: image }?

I’ve got the following CSS to add a PDF icon to any link that links to a PDF:
a.pdf-link:after { padding-left: 2px; content: url(../images/icon-pdf-link.gif);}
Is it possible to put some title and alt attributes on this image? I would like it so that the user is able to hover over the icon and get some text like “This links to a .pdf file.” Which I’ve typically done just by putting title attributes to it, but can’t figure out if I can do that through this method.
No, content only accepts raw text and image data, not HTML.
You need to use JavaScript to dynamically add tooltips to your existing HTML elements.
As for the icon, you could use a background image and some padding:
a.pdf-link {
padding-left: 2px;
padding-right: 20px;
background: url(../images/icon-pdf-link.gif) right center no-repeat;
}
If you need to specifically have a tooltip only on the icon, though, you need to do everything in JavaScript as the comments say.
You can this, these days, using CSS3.
According to https://www.w3.org/TR/css-content-3/#alt:
1.2. Alternative Text for Speech
Content intended for visual media sometimes needs alternative text for speech output. The content property thus accepts alternative text to be specified after a slash (/) after the last . If such alternative text is provided, it must be used for speech output instead.
This allows, for example, purely decorative text to be elided in speech output (by providing the empty string as alternative text), and allows authors to provide more readable alternatives to images, icons, or text-encoded symbols.
Here the content property is an image, so the alt value is required to provide alternative text.
.new::before {
content: url(./img/star.png) / "New!";
/* or a localized attribute from the DOM: attr("data-alt") */
}
Based on the answer I just did the following with jQuery:
$(".pdf-link").before("<img src='../images/icon-pdf-link.gif' title='This link is a pdf' />");

Turn Off Alt Tags On Links With CSS?

This website that I'm working on has annoying alt tags popping up when you hover over links in the sidebar. I didn't put these alt tags in. But, I can control the CSS... Is there anyway to disable them?
Thank you!
Tara
Simple answer: no
They are impossible to turn off just with CSS. They are browser dependant and are not part of any CSS spec i.e. you can't style them, hide them, anything.
Though you can get rid of them by Javascript:
Javascript
var elements = document.getElementsByTagName('a');
for (var i = 0, len = elements.length; i < len; i++)
{
elements[i].removeAttribute('title');
}
They're actually title tags and you can't remove them with css (you can with javascript) but I guess they're there for a reason.
You can use CSS like below:
pointer-events: none;
From what I can see of the site, you’re getting a tooltip when you hover over the side bar links because they each have a title attribute.
I don’t think there’s anything in CSS to prevent these showing up. Showing these in a tooltip on hover is a decision the browser makes, separately to the rendering of the HTML.
The best you can do is use JavaScript to remove the title attribute.
You can use CSS to hide images with any alt text, for example alt = "LinkedIn"
[alt="LinkedIn"] {
display: none !important;
}
You can also hide the image with title for example title = "Company logo"
[title="Company logo"] {
display: none !important;
}
Dear stackoverflow members,
I wanted to remove the img alt attribute, to remove the alt thing, with css, without changing html php, or adding java elements.
I wanted simply this box (border) around the image that is appearring to be removed. I could not find anywhere this simple solution! So i post it here! I hoep will help someone! I include a screenshot.
I made height and width to be exact with the picture, no more, no less.
Also, check that font-size attribute element was set to 0.
That is (dependign on other set attributes, you may also need to adjust them, in order this "box" be adjusted to the exact size of your image:
#your_specific_ID_name .image_myclass_image {
background-position: 0px 0px;
height: 'the height of your image';
width: 'the width of your image';
font-size: 0;
}

Resources