0

One of the simplest image gallery layouts is a square grid with centered images, like the Adobe Lightroom screenshot below.

There are many similar questions (1) (2) (3), but all these involve square images and a square grid. Mine is more general, because it involves rectangular images and a square grid.

I’ve spent a long time trying to reproduce exactly the screenshot below using css flexbox and inline-box, but always failed to get the centering exactly right:

flex: jsfiddle.net/rmodrak/4sxzkonr/

inline-block: jsfiddle.net/rmodrak/wmunqzL6/

It’s hard to believe css doesn’t natively support such a layout. Am I missing something?

enter image description here

rmodrak
  • 65
  • 6

1 Answers1

1

Try this:

Edit: Added responsive layout.

<!DOCTYPE html>
<html>
<head>
<style>
 /*SO relevant*/
 body{
  background:#121212;
  color:white;
 }
 
 /*Container styling*/
 #container{
  /*Important*/
  width:25%;
  min-width:220px; /*200px+subcontainer margin x 2+subcontainer padding x 2*/
  min-height:220px; /*Same here*/
  display:inline-block;
  border:1px solid red; /*If you want to add a border, use box-sizing, see below*/
  box-sizing:border-box; /*Hello im box-sizing man!*/
  padding:0;
  margin:0;
  float: left;
 }
 
 /*Sub-container styling*/
 #subcontainer{
  /*Important*/
  width:200px;
  height:200px;
  position: relative;
  left: 50%;
  -ms-transform: translateX(-52.5%);
  transform: translateX(-52.5%);
  
  /*SO relevant*/
  background:#222222;
  padding:5px;
  margin:5px;
 }
 #subcontainer img{
  /*important*/
  display:block;
  max-height:100%;
  max-width:100%;
  margin:0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
 }
 /*Make it responsive on smaller devices*/
  @media only screen and (max-width: 910px) {#container{width:33.3%;}}
  @media only screen and (max-width: 690px) {#container{width:50%;}}
  @media only screen and (max-width: 470px) {#container{width:100%;}}
</style>
</head>
<body>
 <h2>Nice photos, nice boxes.</h2>
 <p>Now with 100% more responsiveness!</p>

 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/3NgXgXkD/0001.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/h4x1WB2P/0002.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/FRkgK5mp/0003.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/kGrN61gm/0004.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/VvcMLJKs/0005.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/FzgSfh6y/0006.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/MTBVS7br/0007.jpg"></div></div>
 <div id="container"><div id="subcontainer"><img src="https://i.postimg.cc/WpMgY74d/0008.jpg"></div></div>
</body>
</html>
keanu_reeves
  • 350
  • 1
  • 12