Cody Barr
Cody Barr

Reputation: 631

Flexbox Grid with Images - Maintain Aspect Ratio / Proportions

I'm trying to use flexbox to layout something like the following:

 -- ------ --
|  |      |  |
|--|      |--|
|  |      |  |
 -- ------ --

Each corner 'box' has an img within it who's aspect ratio is 1:1 (square). The center 'box' is 3:2.

The problem is for whatever reason the height of the corner boxes and the center box is larger than the hight of the responsive img within it, I'm trying to get them to align perfectly.

How can I get the flex items to line up correctly?

Here's a codepen: https://codepen.io/codybarr/pen/zNgpVK

EDIT: adding display: flex to .container .item fixed the issue in Firefox but not Chrome/Safari. Now the images stretch to be their full resolution height..weird...

img {
  max-width: 100%;
}

@media (min-width: 700px) {
  .main {
    display: flex;
    flex-direction: row;
    background-color: orange;
  }
  .container {
    display: flex;
    flex-direction: column;
  }
  .container.second-column {
    flex: 1 0 60%;
  }
  .container .item {
    display: flex;
  }
  .container.second-column .item {}
  .container.first-column .item:nth-child(1) {
    background-color: blue;
  }
  .container.first-column .item:nth-child(2) {
    background-color: yellow;
  }
  .container.third-column .item:nth-child(1) {
    background-color: red;
  }
  .container.third-column .item:nth-child(2) {
    background-color: green;
  }
}
<head>
  <title>Flex Testing</title>
</head>

<body>
  <h1>Flex Test!</h1>
  <div class="main">
    <div class="container first-column">
      <div class="item">
        <img src="http://i-cdn.phonearena.com/images/article/90741-image/Google-touts-advanced-recipe-search-in-mobile-app.jpg" />
      </div>
      <div class="item">
        <img src="https://lh3.googleusercontent.com/-cigJW9TQSRU/AAAAAAAAAAI/AAAAAAAAABg/Pg3e9ogcsHU/s640/photo.jpg" />
      </div>
    </div>
    <div class="container second-column">
      <div class="item">
        <img src="https://www.inetsolutions.org/wp-content/uploads/2016/01/Capital-Letters-in-URLs-Do-Not-Influence-Google-Rankings.png" />
      </div>
    </div>
    <div class="container third-column">
      <div class="item">
        <img src="http://www.sociallyawareblog.com/files/2016/12/GettyImages-610773752_small.jpg" />
      </div>
      <div class="item">
        <img src="https://s-media-cache-ak0.pinimg.com/564x/b1/e2/db/b1e2dbe6c6b547a2ebc53a49fc3ffa8c.jpg" />
      </div>
    </div>
  </div>
</body>

Upvotes: 2

Views: 878

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 372059

An initial setting of a flex container is align-items: stretch. This means that flex items will expand, by default, to cover the full length of the cross axis of the container.

Consider overriding the default with align-items: flex-start.

 container .item {
   display: flex;
   align-items: flex-start; /* new */
 }

revised codepen

Upvotes: 2

Related Questions