Why Do I Need "Height: Auto" for Responsive Images

Why do I need height: auto for responsive images?

It makes sure the image is always displayed in the original aspect ratio. It's a common technique to realize responsive display of images. The important part is actually to always set only either width or height to soemthin other than auto. The browser will then resize the image, maintaining the aspect ratio.

max-width: 100%; in your code example makes sure the image is never displayed wider than its parent container.

In your code example, setting it is not necessary:

Most <img> have so-called intrinsic dimensions (such as JPG, PNG, GIF). In this case, stating neither width nor height explicitly makes the browser use those intrinsic dimension as a default for the given image. As soon as you specifiy exactly one of these, the other will be set to auto.

What`s the reason that height:auto sometimes it`s 0

This is because when you add the <img> to the html directly, the browser sets the height of the element to the height of the image you provided (unless otherwise specified). When you add the image as a background of a <div> and set the height to auto, it tries to size the div to the height of the content. However, in this case, there is no content -- only a background that will be the background once the div has some height. An empty div has no height. Therefore, if you want the image to be the background of the <div>, it must either contain some content, or have its height set manually.

css height:auto not showing for responsive image

You don't need the pic in the div, you can have that in the img tag.

The img tag can be changed on hover using css

.img:hover {
content:url(NEWPICPATH);
}

See this answer for more details on changing src this way.

HTML - image width and height versus responsive image

Ok, so I finally solved it by inserting width and height to the img tag and in CSS I kept the width: 100%; height: auto; and now it validates and it is also responsive.

Setting width and height attributes on img element on responsive images

Ok, so after quite extensive research and experimentation I've found out that, in truth, it doesn't really matter as long as the aspect ratio is preserved. So the best bet would probably be to use image's original dimensions.



Related Topics



Leave a reply



Submit