AndreKR
AndreKR

Reputation: 33697

HTML5 maintains aspect ratio of images?

I just noticed that Chrome resizes this image keeping its aspect ratio:

<!DOCTYPE html>
<img style="width: 100%; height: 100%;" src="image.jpg">

When the HTML5 doctype isn't there, the image is distorted:

<img style="width: 100%; height: 100%;" src="image.jpg">

This only works when the image's container is the document, it doesn't work if the image is in a div for example.

What is this feature, and can I somehow scale the image to the full window size without removing the doctype?

Upvotes: 5

Views: 264

Answers (2)

BoltClock
BoltClock

Reputation: 724452

This "feature" is exclusive to quirks mode, in which html and body have 100% height, and the heights of top-level elements are made relative to body. In standards mode, html and body act as regular block boxes with auto heights. Since a percentage height cannot be relative to an auto height, height: 100% doesn't take effect and the image keeps its aspect ratio in standards mode.

This is also why body backgrounds display fully in quirks mode, but not in standards mode, when there isn't enough content to fill the page.

To get the quirks-mode behavior in standards mode, set height: 100% on the html element and min-height: 100% on the body element as described here.

Upvotes: 6

Geuis
Geuis

Reputation: 42297

https://codepen.io/anon/pen/OzLrjw

body {
  background: url('http://www.fillmurray.com/200/300'); 
  background-size: cover;
}

Upvotes: 0

Related Questions