Chris Pink
Chris Pink

Reputation: 2027

Flexbox grid proportional scaling

I have a flexbox layout, it's actually 3 x 3 but I can illustrate with 2 x 2 Fiddle

.grid-container {
  width: 480px; /* Max */
  display: flex;
  flex-flow: row wrap;
}

.grid-cell {
  flex: 1;
  background: #ccc;
  width: 50%
}
<div class="grid-container">
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
</div>

So that works but the images don't resize as the grid gets smaller, if I add .grid-cell img { width: 100%;} the cells all fit on one line. If I take away .grid-cell {width: 50%;} the same happens.

Strangely, in Firefox my desired effect is achieved; the grid shrinks proportionately. In Chrome and Safari, even with -webkit- syntax, it behaves as above. The height of each cell remains constant as the grid gets narrower and the image overflows.

Upvotes: 1

Views: 1869

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

Instead of width: 33% try flex: 0 0 33%

.grid-container {
  display: flex;
  flex-flow: row wrap;
}

.grid-cell {
  flex: 0 0 33%;
  background: #ccc;
  box-sizing: border-box;
  padding: 5px;
}

img {
  width: 100%;
}
<div class="grid-container">
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
  <div class="grid-cell"><img src="http://www.bathfringe.co.uk/wordpress/wp-content/uploads/street-icon.jpg"/></div>
</div>

Upvotes: 2

Related Questions