Expanding iframe within Flexbox

2019-02-12 19:28发布

问题:

I am trying to stretch the size of an iframe to fill the remaining space within my web app. I know the maximum space is being allocated for the div (by adding a border), but the iframe height itself is not expanding to fill the entire vertical height.

The problem is the row content iframe is not filling the entire vertical space, even though the flexbox is allocating that space appropriately.

Any ideas?

.box {
  display: flex;
  flex-flow: column;
  height: 100vh;
}
.box .row.header {
  flex: 0 1 auto;
}
.box .row.content {
  flex: 1 1 auto;
}
.box .row.footer {
  flex: 0 1 40px;
}
.row.content iframe {
  width: 100%;
  border: 0;
}
<div class="box">
  <div class="row header">
    <h1>Event Details</h1>
    <div id="container">
      <h5>Test</h5>
    </div>
    <div data-role="navbar">
      <ul>
        <li><a href="players.html" class="ui-btn-active ui-state-persist">Players</a>
        </li>
        <li><a href="games.html">Games</a>
        </li>
        <li><a href="chat.html">Chat</a>
        </li>
      </ul>
    </div>
  </div>
  <div class="row content">
    <iframe src="players.html"></iframe>
  </div>
  <div class="row footer">
    <p><b>footer</b> (fixed height)</p>
  </div>
</div>

回答1:

Here are two things to consider:

  1. When you create a flex container only the child elements become flex items. Any descendants beyond the children are not flex items and flex properties don't apply to them.

    Your iframe is not a flex item because it is a child of div class="row content" which is a flex item, but not a flex container. Therefore, no flex properties apply and there is no reason for the iframe to stretch.

  2. To apply flex properties to the children of flex items, you need to make the flex item also a flex container. Try this:

    .box .row.content {
        flex: 1 1 auto;
        display: flex; /* new */
    }
    

With the adjustment above the iframe's parent becomes a (nested) flex container, the iframe becomes a flex item, and default flex settings (including align-items: stretch) go into effect. The iframe should now occupy the full height of the container.



回答2:

You can fix it with just flexbox, Make sure the container (wrapper) of the iframe has a height set or its parent has, this can be a in pixels percent or VH. and flex-direction:column. The iframe itself needs a flex:1 1 auto; nothing else is needed so no height or width set on it.

Internet explorer can have some problem with the width of the iframe. But it should work vertically. For IE11 make sure you set a min-height:0 on the wrapper.

body{
  padding:1em;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content: center;
  height:100vh;
}

.wrap {
  display: flex;
  flex-direction: column;
  width: 80vw;
  height: 80vh;
  border: 2px solid blue;
  min-height: 0;
}

.frame {
 flex: 1 1 auto;
 border: 0;
}

Simplified jsfidle demo Complex jsfidle demo