An example of how CSS grid layout can be used to create a dense grid of items even when items have varied widths and heights.
A Pen by Aidan Breen on CodePen.
An example of how CSS grid layout can be used to create a dense grid of items even when items have varied widths and heights.
A Pen by Aidan Breen on CodePen.
<h1>Sexy Food Blog</h1> | |
<div class="container"> | |
<div class="item grid-tail">Sexy food makes sexy people</div> | |
</div> | |
<footer>Made with ♥ by <a href="https://github.com/aido179">Aidan Breen</a></footer> |
$(document).ready(function(){ | |
var maxArea = 9; //cols * rows in grid | |
var areaForTiles = maxArea-1; //subtract space for footer tile | |
var area = 0; //area used by tiles | |
var i = 1; //lets us get unique images from API | |
while(area<areaForTiles){ | |
var w = 1; //actual unit width of current tile | |
var l = 1; //actual unit length... | |
var tileArea = w*l; | |
var wide = ""; //string for css class | |
var tall = ""; | |
if(area<(areaForTiles-tileArea) && Math.random()>0.8){ | |
wide = "double-width"; | |
w = 2; | |
tileArea = w*l; | |
} | |
if(area<(areaForTiles-tileArea) && Math.random()>0.8){ | |
tall = "double-height"; | |
l = 2; | |
tileArea = w*l; | |
} | |
area += tileArea | |
var imgwidth = 400*w | |
var imgheight = 400*l | |
$(".container").prepend(` | |
<div class='item item${i} ${wide} ${tall}'> | |
</div> | |
`); | |
$(`.item${i}`).css('background-image', `url("http://lorempixel.com/${imgwidth}/${imgheight}/food/${i}")`); | |
i+=1; | |
} | |
}); |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> |
body{ | |
margin:0; | |
font-family: 'Playfair Display', serif; | |
} | |
h1{ | |
font-family: 'Dawning of a New Day', cursive; | |
text-align:center; | |
font-size:2em; | |
} | |
.container{ | |
width:300px; | |
height:600px; | |
margin: auto; | |
display:grid; | |
grid-auto-flow: dense; | |
grid-template-columns: 1fr 1fr; | |
grid-gap: 10px; | |
} | |
.item{ | |
width:100%; | |
max-height:100%; | |
min-height:100px; | |
background-color:#333; | |
background-size:cover; | |
} | |
.double-width{ | |
grid-column-end: span 2; | |
} | |
.double-height{ | |
grid-row-end: span 2; | |
} | |
.grid-tail{ | |
background-color:#fff; | |
font-size:2.5em; | |
grid-column-end: span 2; | |
} | |
footer{ | |
height:100px; | |
width:100vw; | |
display: table-cell; | |
text-align:center; | |
vertical-align: bottom; | |
color:#7b6d63; | |
} | |
footer a{ | |
color:#333; | |
} | |
@media only screen and (min-width: 600px) { | |
h1{ | |
font-size:4em; | |
} | |
.container { | |
width:450px; | |
} | |
.grid-tail{ | |
grid-column-end: span 1; | |
} | |
} | |
@media only screen and (min-width: 800px) { | |
.container { | |
width:600px; | |
grid-template-columns: 1fr 1fr 1fr; | |
} | |
} |