Newline in alt text

2019-02-06 05:57发布

问题:

Can I use some sort of line break in the alt text for an image while still adhering to the XHTML 1.0 Strict standard?

Something like this...

<img src="foo.jpg" alt="Line 1\nLine 2" />

I'm asking because I want to post the following screenshot on my site, but I want to include the text-only version in the alt text for SEO reasons and for the visually impaired.

I prefer the screenshot over the plain text version because it looks more visually appealing.

回答1:

Just use a normal line break.

<img src="foo.jpg" alt="Line 1
Line 2" />

Stack Overflow does this in their titles :)

Then add this CSS:

img{white-space:pre}

Demo: http://jsfiddle.net/Madmartigan/S8SXP/



回答2:

A better way is to just add the HTML character code for line feed or carriage return.

 line feed is &#10
 carriage return &#13


回答3:

I think you might be trying too hard.
The alt text is supposed to be a replacement for the image, not some kind of literal representation of it.

Properly marked up and so on, this would be say an unordered list with sub-lists, and a screen-reader would get relationship information from that nesting of HTML elements. Replacing that with some line breaks to get a rough visual approximation isn't nearly the same thing, eg. how do you plan to also "show" the screenreader that the chunk after the first line break is "inside" the Errors?
And I doubt search engines are going to do anything with line breaks in alt text other than discard them. (Admittedly speculative.)

What you're actually after is somehow including that nesting/relationship information the image has, but with text instead. Start with something like "A screenshot of notices from [app], showing two errors [detail here if you want] and two informational items [detail]" etc.

Or you could get really pedantic and actually create the list in HTML, then use an image replacement technique to insert the image.



回答4:

@Murch's answer was something I didnt know. However it becomes and overhead to break whitespaces to BRs all throughout the app.

As the simplest solution, you can just provide

img.class { overflow:hidden }

and get over with it quick and dirty.



标签: html xhtml