CSS height 100

2019-06-12 19:51发布

JSFiddle: https://jsfiddle.net/570qvk2p/1/

I have a third-party html document that I am embedding in an iframe. Within this document there is an element with a css rule specifying height: 100%; A parent some steps up the tree has a fixed height.

When rendering the third party HTMLDocument in its original form, the element with 100% height assumes a size of 18px (fitting to content). When rendering inside an iframe, the element assumes the size of the fixed height parent (200px).

Why would sizing work differently within the iframe and how can I counteract that?

The following is the html that you can see from the fiddle ends up styled different when inserted into an iframe vs when inserted into the top level document:

<div style="height: 200px;">
  <ul style="display:block;">
    <li>
      <div style="height: 100%;">1</div>
    </li>
    <li>
      <div style="height: 100%;">2</div>
    </li>
    <li>
      <div style="height: 100%;">3</div>
    </li>
  </ul>
</div>

This question: Element in iframe with height: 100% strech describes the same phenomenon, but that particular case is solvable for me by setting a size on the html tag before deferring to the iframe size. What I am showing above seems to be a more general case of the same issue described by that person.

标签: html css iframe
1条回答
Deceive 欺骗
2楼-- · 2019-06-12 20:22

Your iframe has no doctype which seems to be causing the rendering issues.

Constructing your iframe with a defined doctype gives consistent rendering between your page and iframe:

var doc = window.frames[0].document;

var a = doc.createElement("div");
var b = document.createElement("div");
var content = "<div style=\"height: 200px;\"><ul style=\"display:block;\"><li><div style=\"height: 100%;\">1</div></li><li><div style=\"height: 100%;\">2</div></li><li><div style=\"height: 100%;\">3</div></li></ul></div>";

doc.open();
doc.write("<!DOCTYPE html>");
doc.write("<html>");
doc.write("<head></head>");
doc.write("<body>" + content + "</body>");
doc.write("</html>");
doc.close();

b.innerHTML = content;
document.body.appendChild(b);

Updated jsfiddle

I was under the impression that an iframe inherited the doctype of the parent page but this doesn't seem to be the case. Perhaps somebody else can elaborate?

查看更多
登录 后发表回答