HTML and CSS Reference
In-Depth Information
Add Width and Height to an Image
Add
width
and
height
attributes to all
img
elements that don't have them.
<img src="winter.jpg" alt="Frozen river" />
<img src="winter.jpg" width='640' height='480'
alt="Frozen river" />
Motivation
width
and
height
attributes enable a browser to format a page much more quickly and display it to the user
sooner. This is especially critical on slow dial-up connections, which about 20% of web surfers still use.
Potential Trade-offs
If you change the size of the images, you'll also need to change the HTML. Otherwise, the pictures may be
strangely compressed or expanded. If you're frequently changing images—for instance, while designing a
page—you may wish to leave the insertion of widths and heights to the final prepublication stage.
Mechanics
The XHTML DTD does not require
width
and
height
attributes on
img
elements, so simple validation will not
find the problem. However, a regular expression can find missing
width
attributes. The trick is to match all
possible attributes except
width
and
height
, like so:
<img\s+((alt|border|class|align|id|src|usemap|hspace|vspace)
\s*=\s*("[^"]+"|'[^']+')\s*)*>
Only
img
tags that do not contain
width
and
height
attributes will match. (Here we're relying on the absence of
weird, unexpected attributes. In essence, validity is a weak prerequisite for this search.)
If you think you might have remembered to add a
height
but not a
width
or vice versa, check these regular
expressions:
<img\s+((width|alt|border|class|align|id|src|usemap
|hspace|vspace)\s*=\s*("[^"]+"|'[^']+')\s*)*>
<img\s+((height|alt|border|class|align|id|src|usemap
|hspace|vspace)\s*=\s*("[^"]+"|'[^']+')\s*)*>
That should sniff out all the missing sizes.
If you find only a few such elements, you might as well open the files, load the relevant images into a program
that will tell you their size, and fix them manually. Firefox helpfully shows the image width and height when you
open an image directly (as opposed to the HTML page in which the image is embedded).
Search WWH ::
Custom Search