Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flexbox, responsive grid of square divs maintaining aspect ratio

I'm trying to create a 2x2 grid with divs. Some of the divs might contain an image, but it will probably be set as a background, with the option background-size: cover.

Here's the pen I created: http://codepen.io/qarlo/pen/vLEprq

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: auto;
  max-width: 960px;
  width: 80%;
}
.container__item {
  align-content: center;
  border: 1px solid #333;
  display: flex;
  flex-basis: 1;
  font-size: 3em;
  justify-content: center;
  height: 100%;
  margin-bottom: 1em;
  min-height: 300px;
  width: 47%;
}
<div class="container">
  <div class="container__item">?</div>
  <div class="container__item">?</div>
  <div class="container__item">?</div>
  <div class="container__item">?</div>
</div>

I'd like to force the divs to be squares and maintain the aspect ratio when resizing it. I was mistakenly hoping that this would have been straightforward with flexbox, but unless I'm missing something, I was wrong.

like image 715
Carlo Avatar asked Dec 08 '15 09:12

Carlo


2 Answers

To maintain your items aspect ratio, a very simple method is to use CSS Viewport units

I modified your pen to see how this units work: http://codepen.io/vladbicu/pen/wMBmOb

.container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin: auto;
    max-width: 960px;
    width: 80%;
}

.container__item {
    align-content: center;
    border: 1px solid #333;
    display: flex;
    flex-basis: 1;
    font-size: 3em;
    justify-content: center;
    margin-bottom: 1em;

    // maintain aspect ratio
    width: 30vw;
    height: 30vw;
}

Hope it helps.

like image 75
Vlad Bîcu Avatar answered Sep 20 '22 06:09

Vlad Bîcu


Use the old "padding-bottom" trick for fixed aspect ratio. Extra divs are reqiured though:

.container {
  margin: auto;
  width: 80%;
  max-width: 960px;
}
.container__square {
  float: left;
  position: relative;
  padding-bottom: 50%;
  width: 50%;
  background: linear-gradient(45deg, #CCC, #000, #CCC);
}
.container__square__item {
  position: absolute;
  top: 1em;
  bottom: 1em;
  left: 1em;
  right: 1em;
  border: 1px solid #333;
  background: #FFF;
}
/* clearfix */
.container::after {
  content: "";
  display: block;
  clear: both;
}
<div class="container">
  <div class="container__square">
    <div class="container__square__item">?</div>
  </div>
  <div class="container__square">
    <div class="container__square__item">?</div>
  </div>
  <div class="container__square">
    <div class="container__square__item">?</div>
  </div>
  <div class="container__square">
    <div class="container__square__item">?</div>
  </div>
</div>
like image 31
Salman A Avatar answered Sep 22 '22 06:09

Salman A