Achieving a Photo Grid Layout with CSS

Looking for help with my CSS photogrid - it's close to what I want, but not quite there. Here's the layout I'm aiming for:

1 | 2 | 3
4 | 5 | 6

But currently, it displays like this:

1 | 3 | 5
2 | 4 | 6

I've tried tweaking the CSS but couldn't achieve the desired layout. Below is the code I'm using:

HTML:

<section id="photos">
<img src="imgs/logo1.jpg" alt="">
<img src="imgs/logo2.png" alt="">
<img src="imgs/logo3.png" alt="">
<img src="imgs/logo4.jpg" alt="">
</section>

CSS

#photos {
  /* Prevent vertical gaps */
  line-height: 0;

  -webkit-column-count: 5;
  -webkit-column-gap:   0px;
  -moz-column-count:    5;
  -moz-column-gap:      0px;
  column-count:         5;
  column-gap:           0px;  
}

#photos img {
  /* Just in case there are inline attributes */
  width: 100% !important;
  height: auto !important;
}

@media (max-width: 1200px) {
  #photos {
  -moz-column-count:    4;
  -webkit-column-count: 4;
  column-count:         4;
  }
}
@media (max-width: 1000px) {
  #photos {
  -moz-column-count:    3;
  -webkit-column-count: 3;
  column-count:         3;
  }
}
@media (max-width: 800px) {
  #photos {
  -moz-column-count:    2;
  -webkit-column-count: 2;
  column-count:         2;
  }
}
@media (max-width: 400px) {
  #photos {
  -moz-column-count:    1;
  -webkit-column-count: 1;
  column-count:         1;
  }
}

Answer №1

One effective way to gain more control over the element's order using CSS is by utilizing the flexbox feature. Key flex properties for achieving this include flex-direction and order.

Illustrations of Flex Direction:

.container {
    display: -webkit-flex; /* Safari */    
    display: flex;
    outline: 1px dashed black;
    color: white;
    font-size: 2em;
}

.row {
    -webkit-flex-direction: row; /* Safari 6.1+ */
    flex-direction: row;
    background: tomato;
}

.row-reverse {
    -webkit-flex-direction: row-reverse; /* Safari 6.1+ */
    flex-direction: row-reverse;
    background: gold;
}

.column {
    -webkit-flex-direction: column; /* Safari 6.1+ */
    flex-direction: column;
    background: hotpink;
}

.column-reverse {
    -webkit-flex-direction: column-reverse; /* Safari 6.1+ */
    flex-direction: column-reverse;
  background: purple;
}

.container div {
    padding: 5px;
    outline: 1px solid cyan;  
}
<div class="container row">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div>
</div>

<div class="container row-reverse">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div>
</div>

<div class="container column">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div>
</div>

<div class="container column-reverse">
<div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div>
</div>

Examples of Flex Order:

.orderA, .orderB, .orderC {
  outline: 1px dashed black;
  display: -webkit-flex; /* Safari */
  display: flex;
  font-size: 2em;
}

.orderA .a {
  -webkit-order: 1;
  order: 1;  
}

.orderA .b {
  -webkit-order: 2;
  order: 2;  
}

.orderA .c {
  -webkit-order: 3;
  order: 3;  
}

.orderA .d {
  -webkit-order: 4;
  order: 4;  
}

.orderA .e {
  -webkit-order: 5;
  order: 5;  
}

.orderA .f {
  -webkit-order: 6;
  order: 6;  
}

.orderB .a {
  -webkit-order: 6;
  order: 6;  
}

.orderB .b {
  -webkit-order: 5;
  order: 5;  
}

.orderB .c {
  -webkit-order: 4;
  order: 4;  
}

.orderB .d {
  -webkit-order: 3;
  order: 3;  
}

.orderB .e {
  -webkit-order: 2;
  order: 2;  
}

.orderB .f {
  -webkit-order: 1;
  order: 1;  
}

.orderC .a {
  -webkit-order: 2;
  order: 2;  
}

.orderC .b {
  -webkit-order: 4;
  order: 4;  
}

.orderC .c {
  -webkit-order: 6;
  order: 6;  
}

.orderC .d {
  -webkit-order: 1;
  order: 1;  
}

.orderC .e {
  -webkit-order: 3;
  order: 3;  
}

.orderC .f {
  -webkit-order: 5;
  order: 5;  
}

.orderA div {
  background: skyblue;
  outline: 1px solid hotpink;
  padding: 5px;
}

.orderB div {
  background: gold;
  outline: 1px solid hotpink;
  padding: 5px;
}

.orderC div {
  background: greenyellow;
  outline: 1px solid hotpink;
  padding: 5px;
}
<div class="orderA">
<div class=a>1</div><div class=b>2</div><div class=c>3</div><div class=d>4</div><div class=e>5</div><div class=f>6</div>
</div>

<div class="orderB">
<div class=a>1</div><div class=b>2</div><div class=c>3</div><div class=d>4</div><div class=e>5</div><div class=f>6</div>
</div>

<div class="orderC">
<div class=a>1</div><div class=b>2</div><div class=c>3</div><div class=d>4</div><div class=e>5</div><div class=f>6</div>
</div>

An Attractive Grid of Images with Flexible Layout where flex-direction and order features can be effortlessly incorporated (when necessary):

body {
  width: 100%;
  height: 100vh;
  margin: 0;
}

.container {
    display: -webkit-flex; /* Safari */    
    display: flex;
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
    -webkit-justify-content: space-around; /* Safari 6.1+ */    
    justify-content: space-around;
}

.container div {
  -webkit-flex: 0 0 calc(33.3% - 20px); /* Safari 6.1+ */
  -ms-flex: 0 0 calc(33.3% - 20px); /* IE 10 */ 
  flex: 0 0 calc(33.3% - 20px);  
  background: lavender;
  border: 2px solid black;
  box-sizing: border-box;
  margin: 10px;
  font-size: 2em;
  text-align: center;
}
<div class="container">
  <div>1 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
  <div>2 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
  <div>3 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
  <div>4 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
  <div>5 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
  <div>6 <img src="http://i.imgur.com/ufh1gnC.png" alt=img></div>
</div>

Answer №2

For those who appreciate the Mosaic style, here's an alternative method to arrange images using Javascript: "Always place the Image in the shortest column".

  1. Position Images absolutely, and make the Div container relative.
  2. Utilize an array to store the height of each column: var columnsHigh = [0,0,0]
  3. Iterate through the image list, selecting one at a time and placing it at coordinates {x,y}, with y = min(columnsHigh) and x = 100/(minPos(columnsHigh, y)) (minPos will identify the index of the shortest column in the columsHigh array.)
  4. Adjust the height of the container and the shortest column by adding the height of the image.

Demo Code

$(function(){
mosaicGrid('.container', 'img');
});

function mosaicGrid(selector,target) {
  var cols = [0,0,0,0];
  var allTarget = $(selector).find(target);
  if (0 === allTarget.length) 
    return;
  allTarget.one('load', function(e){    
      var pos = minPos(cols);
      var x = pos * 100/cols.length;
      var y = cols[pos];
      $(this).css({left: x + "%", top: y + "px", width: Math.floor(100/cols.length)+"%"});      
      cols[pos] = cols[pos] + $(this).height();
      $(selector).height(Math.max.apply(null, cols) );      
      $(this).off(e);
  }).each(function(){
    if(this.complete)
      $(this).trigger('load');
  });
}
function minPos(arr) {
  var min = Math.min.apply(null, arr);
  for(var i = 0; i < arr.length; i++) {
    if (min === arr[i])
      return i;
  }
}
.container {
  position: relative;
  width: 100%;
  height: 50px;
}

img {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <img src="http://www.warrenphotographic.co.uk/photography/cats/30081.jpg" alt="">
  <img src="http://iwallhd.com/stock/yellow-labrador-retriever-puppy-white-background.jpg" alt="">
  <img src="http://i.imgur.com/nZlaeSH.jpg" alt="">
  <img src="http://www.cuter.cn/wp-content/uploads/2013/08/1375453731.jpg" alt="">
  <img src="https://puppydogweb.com/wp-content/uploads/2015/05/puppy-wallpaper-dancing-little-dogs-.jpg" alt="">
  <img src="http://www.petsworld.in/blog/wp-content/uploads/2015/03/How-To-Make-Your-Puppy-Gain-Weight.jpg" alt="">
  <img src="http://www.dogster.com/wp-content/uploads/2015/05/dalmatian-puppies-04.jpg" alt="">
  <img src="http://indiabright.com/wp-content/uploads/2015/10/Gallery-of-Dogs-Balancing-Cupcakes-539445.jpg" alt="">
  <img src="https://s-media-cache-ak0.pinimg.com/236x/63/60/39/6360396daf54afd024d181b6567a8c28.jpg" alt="">
  <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSr7jvGrFyqNOWgqfMD5t5zgOOf66pfGLVM8Jv0Uj16gfufLQTF" alt="">
  <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcR24wc_yoDK_i3nm6o6IV77ggd9KzBiBR9wwBlU3-bIgIEz9bMT" alt="">
  <img src="http://justcuteanimals.com/wp-content/uploads/2015/01/puppy-love-cute-yellow-lab-puppies-pups-dogs-animals-pictures-pics.jpg" alt="">
  <img src="http://omgcutethings.com/wp-content/uploads/2014/08/puppy-love-005-08092014.jpg" alt="">
  <img src="http://www.dallasvoice.com/wp-content/uploads/2015/03/puppy-2.jpg" alt="">
  <img src="http://www.perseyspetgrooming.com/images/puppy.png" alt="">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activating the CSS :active selector for elements other than anchor tags

How can I activate the :active state for non-anchor elements using JavaScript (jQuery)? After reading through Section 5.11.3 of the W3C CSS2 specification in relation to the :hover pseudo selector in hopes of triggering the activation of an element, I stu ...

What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation. Here's my CSS: h3[id="balance-desktop"]{ color: black; -webkit-animation-name: gogreen; -webkit-animation-duration: 2s; animation-name: gogreen; animation-du ...

Displaying a project in the same location using jQuery

Struggling with jQuery and positioning hidden items that need to be shown? I have two white boxes - the left one is the Client Box (with different names) and the right one is the Project Box (with different projects). My goal is to show the projects of a c ...

The overflowing pop-up container

When I trigger a popup that dynamically generates a fixed background with a centered dialog, it works well. However, on smaller monitors like laptops, tablets, and phones, the content can overflow beyond the visible area due to its fixed container, making ...

Steps for altering the color of an element when it hovers over a different element

I'm curious if it's possible to achieve something similar using CSS and how can I do it? HTML: <h2 id="hi">Hello!!! :) </h2> <h3 id="bye">Bye!! :( </h3> CSS: #hi:hover { #bye { color: green; } } ...

Stacking parent elements above children in CSS styling

I am encountering an issue with the following DIV structure: <div id="parent"> <div id="child"></div> <div id="child2"></div> </div> My goal is to have a partially opaque background for the parent DIV and fully visible ...

Easily validate the contenteditable attribute of <td> element

I am currently working on a table that displays data from a MYSQL database. Whenever a user makes changes to an element in the table, I want the database to be updated using AJAX. Below is my JavaScript code for sending data in an editable row. function s ...

How do I dynamically incorporate Tinymce 4.x into a textarea?

I am encountering a small issue when trying to dynamically add tinymce to a textarea after initialization. tinymce.init({ selector: "textarea", theme: "modern", height: 100, plugins: [ "advlist autolink image lists charmap print p ...

Center two distinct elements using Bootstrap's center-block class

Check out my code snippet below: <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="center-block" style="w ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

The function of slidetoggle is malfunctioning when clicked

I currently have two dynamic containers with one displaying grouped boxes, quantities, and totals, while the other shows detailed information. Both container values are added dynamically at runtime. By default, the grouping container is displayed on the p ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

What is the best way to transfer form data stored locally to a Django view and then store it in the database?

Is there a way to transfer form data from an offline website to a Django view for database storage? I want to fill out a form, save it in local storage, and then upload the data to the database when I reconnect to the internet. Is there a tutorial or can ...

using angularjs to dynamically apply css styles

Below is the input I have: The HTML code is shown below: <input type="number" ng-class="{negative: amount < 0}" ng-model="amount"/> This is the corresponding CSS code: .negative { color: red; } If the amount is positive, no specif ...

Can AngularJS support HTML5-mode URL routing in locally stored files (using the file:// protocol)?

Sorry if this question has already been asked, but I haven't been able to find any information on it. I'm working on an AngularJS application that needs to be accessed directly from a hard drive (not through a traditional HTTP server), so the UR ...

JavaScript-generated div not recognizing CSS in Internet Explorer

Once again, dealing with Internet Explorer has become a major headache. On headset.no, we have incorporated a small blue search field. However, when you input "jabra" into the field, it should generate suggestions in a div underneath. This feature operates ...

A JavaScript function that is only triggered half of the time

After browsing through various forums like StackOverflow, I couldn't find a solution that perfectly fits my issue. I may be new to programming, but I've managed to create several projects already. Currently, I am working on integrating them into ...

Is there a way to retrieve the row and parent width from a Bootstrap and Aurelia application?

Is there a way to determine the exact width of a bootstrap grid row or grid container in pixels using Aurelia? I attempted to find this information on the bootstrap website, but I am still unsure as there are multiple width dimensions such as col-xs, colm ...

Challenges with resizing images in SVG using D3

I have an SVG image created using d3. I am facing an issue where the svg is extending beyond its parent div container. Here is the code snippet: <div id="test" style="{width: 500px; height:500px;}"> <svg></svg> </div> ...