Iframe vs. div in absolute positioning

2019-04-14 05:27发布

问题:

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.

回答1:

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.



回答2:

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>



标签: html css iframe