The HTML IMG
attributes and styling that I think I want
Once upon a long time ago,
I put very basic support for inline images into DWikiText (the
wikitext dialect used here). At the time I felt I had both simple
needs and a simple understanding of the IMG
element, so I just
specified the image's width and height and called it a day, putting
them in as width=
and height=
attributes in the IMG
element.
Much later on, on my personal site, I found that I wanted to include some images and make them as large as would fit in my layout. So I did a hack; I carefully worked out the rough largest image width that would fit in my own browser window in the relatively narrow width I normally keep it at, resized my images to be that wide, and called it a day. This worked for a while (as far as I could see) but then I got an iPhone and looked at my own site with it. The results were not appealing; with my nominally responsive CSS my fixed-width images somehow had tha paradoxical effect of forcing the text content to be narrower (and in a smaller font size) than it could be.
So I did some fiddling to see if I could do better. I decided that I wanted my inlined images to have the following behavior:
- never push the natural (text) content width wider (much like how I
now want all
<pre>
content to behave) - shrink down in size instead of getting truncated as the content width shrinks
- preserve their aspect ratio as the content width shrinks or grows
- don't enlarge themselves beyond their full size, because my inlined images don't necessarily look good zoomed up
Based on both experimentation and reading the MDN page on <img>
,
what I seem to want is <img>
tags that specify a width=
value
(in pixels) but not a height=
, combined with the CSS style of
'max-width=100%
'. The CSS max-width
gets me my first two things,
specifying width
appears to mean that browsers won't enlarge the
image, and not specifying height
appears to make browsers preserve
the image aspect ratio if and as they shrink the image. Specifying
height
as well as width
caused at least some browsers to not
preserve the aspect ratio, which sort of vaguely makes sense if I
squint at it enough.
(You can also put in invalid values for height
, like 'x
', and
get the same effect.)
This feels a bit like a hack, especially the bit about omitting
height=
, but it also appears to work. Probably there are some
less than desirable effects on page layout on slow networks, but
I'll live with them unless I can find a better way.
(Some sources suggest that I should set the CSS height
to 'auto
'
as well. The whole area of scaling images to fit in content areas
appears to be rather complicated, based on some Internet searches,
or perhaps most everyone is over-engineering it with Javascript and
lots of CSS and so on. I'm pretty ignorant about the modern state
of CSS, so I'm definitely working by superstition.)
|
|