user4351667
user4351667

Reputation:

Iframe vs. div in absolute positioning

I wonder why the following iframe doesn't stretch to cover the whole page:

* {
  margin: 0;
  border: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
body {
  position: relative;
}
iframe {
  display: block;
  background: tan;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
<iframe></iframe>

However, a div stretches as expected.

Upvotes: 2

Views: 1331

Answers (2)

Alohci
Alohci

Reputation: 82976

A div is a non-replaced element. When you absolutely position it, its width is given by the CSS rules defined in 10.3.7 Absolutely positioned, non-replaced elements - specifically in your case, the width is determined in step 5. Essentially the equation

'left' + 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' + 'right' = width of containing block

is used where in your CSS all the values are fixed except width, so width is computed to make the equality hold.

An iframe is considered a replaced element. When you absolutely position it, its width is given by the CSS rules defined in 10.3.8 Absolutely positioned, replaced elements which defers the width calculation to the last line of the rules for 10.3.2 Inline, replaced elements - i.e. the iframe does not have an intrinsic width, so its width is computed to be typically 300px. This is similar to the img element, which also won't expand to fill the page with the same CSS rules. But images normally do have an intrinsic width, so that width is used rather than 300px.

Similar rules apply for the height calculation.

Upvotes: 1

Alex
Alex

Reputation: 8695

Give width:100%; and height:100; to iframe.

* {
  margin: 0;
  border: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
body {
  position: relative;
}
iframe {
  display: block;
  background: tan;
  /* position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0; */
  width:100%;
  height:100%;
}
<iframe></iframe>

Upvotes: 0

Related Questions