简体   繁体   中英

Image height and width when image not found

I have the following code:

<div>
  <img src="../images/curry.jpg" height="242" width="300" 
       alt="Can't find image (http://localhost/images/curry.jpg)">
</div>

I am trying to precisely lay out a page so, even if the image is not found, I would like the Alt text to occupy the given height & width.

1) is that now how HTML/CSS works?

2) if not, since I generating the HTML from PHP, is there anything I can do to achieve what I want? For instance, would it work if I check for non-existence and instead of an IMG tage, generate a Fieldset of the desired size, containing my Alt text?

The answer to you first question is Yes. Alt attribute is for SEO purposes, and behaves as you have seen it.

It is possible although I must warn you of additional overhead, there is a function file_exists() to check if the image is existent.

If that function returns false instead of echoing the image just echo " <p>Can't find image (http://localhost/images/curry.jpg)</p> " and add a style attribute to the wrapping div that states your desired width and height

<div style='height: 242px;width: 300px'>

If you're generating the page using PHP you can just fix the width / height of the div.

As for the "Alt Text" could you show a small screenshot of what you want? I don't really understand by what you mean by occupying the given size.

What happens when the browser can't find the image depends on the browser. Just have a look at this in a few browsers and see what happens:

http://jsfiddle.net/nhHyC/

Safari uses the specified dimensions but displays the "broken image" icon in that space.

Firefox 4 uses the alt text but ignores the dimensions.

Opera and Chrome use the specified dimensions and display the alt text in that space.

I didn't bother checking IE because those machines are hidden in the closet of my testing labs:)

If you need specific behavior then you'll have to do it yourself with a wrapper <div> with display:inline-block and the desired dimensions. Arranging the appropriate content will be trickier if you want to cover all the browsers.

The alt attribute is meant for user agents that cannot display images (such as screen readers and text only devices):

For user agents that cannot display images, forms, or applets, this attribute specifies alternate text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM