Search code examples
htmlcssiframe

Centering CSS grid divs with iFrame and Img


So I want to create a grid on my site that has 2 i frames at the top and 2 imgs below e.g

X X
X X

I have managed to get some code working, but it doesn't look quite right, right now the grid is stuck to the left-hand side of the page and in mobile view it just goes off the screen and doesn't fit to a mobile version, another issue is there is a random gap between each column. E.g below.

iframe {
  border: 1px solid;
}

.plotly-charts {
  justify-content: center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 5px;
}
<div class="plotly-charts">
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Positive" style="width:300px; height:300px;">
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Negative-Neutral" style="width:300px; height:300px;">
  </div>
</div>


Solution

  • Remove width/height attributes from iframe, make it flexible with CSS, also remove inline styles from you images and make it responsive. Also, make .charts flex. In this case you can align this cells' content.

    See CSS Code snippet part comments for more details.

    Expand Code snippet to fullpage, to see example

    .plotly-charts {
      display: grid;
      grid-template-columns: 1fr 1fr;
      /* add grid gaps (gaps between rows and columns) */
      column-gap: 1rem;
      row-gap: 1rem;
    }
    
    /* make cell flex */
    .charts {
      display: flex;
      justify-content: center;
    }
    
    .charts iframe {
      width: 100%;
      /* you can add ratios to your iframe in other way */
      aspect-ratio: 6/5;
    }
    
    /* add styles to you images, make it responsive */
    .charts img {
      height: auto;
      width: 100%;
    }
    
    /* added for example purposes */
    .charts iframe, .charts img {
      max-width: 600px;
    }
    <div class="plotly-charts">
      <div class="charts">
        <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/3.embed?logo=false&link=false&autosize=true"></iframe>
      </div>
      <div class="charts">
        <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/1.embed?logo=false&link=false&autosize=true"></iframe>
      </div>
      <div class="charts">
        <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Positive">
      </div>
      <div class="charts">
        <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Negative-Neutral">
      </div>
    </div>