Aligning a flex container in the middle of the horizontal axis

Is there a way to horizontally center a grid of images created with flex while still keeping the images left-aligned on each row? I want this layout to adjust dynamically based on the number of elements per row.

Check out my Jsfiddle attempt here

.gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: flex-start;
  align-items: flex-start;
}

.gallery-artwork {
  width: 400px;
  display: flex;
  margin: 10px;
}
<div class="gallery">
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
</div>

Answer №1

This method is suitable for handling various elements and widths.

https://jsfiddle.net/p01mx39h/14/

function addDummies() {
  imgsPerRow = Math.floor($(".gallery").width() / $(".gallery-artwork").outerWidth(true));
  if (imgsPerRow > 1) {
    missingImages = imgsPerRow - $(".gallery-artwork").length % imgsPerRow;
    while (missingImages > 0) {
      $(".gallery").append("<div class='gallery-artwork-dummy'></div>");
      $(".gallery-artwork-dummy").css('width', $('.gallery-artwork').outerWidth(true));
      missingImages--;
    }
  }
}

$(document).ready(function() {
addDummies();
});
.gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  align-content: flex-start;
  align-items: center;
}

.gallery-artwork {
  width: 400px;
  display: flex;
  margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gallery">
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
</div>

Answer №2

It has been widely discussed both here and on various websites that using dummy elements is currently necessary for achieving the desired layout. Here's a simple method to implement this in pure JavaScript without any complex calculations:

  • Create dummy elements equal to the number of .gallery-artwork elements
  • Style these dummies similarly with no height or vertical margins

This approach offers a significant advantage as it eliminates the need for calculations. By ensuring you always have enough dummies, regardless of screen width or the number of elements per row, you can easily align your content to the left side of the container.

Below is the code snippet to achieve this:

var gallery = document.querySelector('.gallery'),
    artworks = gallery.querySelectorAll('.gallery-artwork'),
    dummy = document.createElement('div');
dummy.classList.add('gallery-dummy');

// Create one dummy element for each artwork
[].forEach.call(artworks, function() {
  gallery.appendChild(dummy.cloneNode());
});
.gallery {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
.gallery-artwork {
  width: 400px;
  margin: 10px;
}
.gallery-dummy {
  width: 400px;
  margin: 0 10px;
  height: 0;
}
<div class="gallery">
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
  <div class="gallery-artwork">
    <img src="http://placehold.it/400x225">
  </div>
</div>

Answer №3

  • To achieve center alignment, simply wrap an element around the content and apply normal centering techniques.
  • If you want left-aligned flex items within a centered layout, use justify-content: flex-start by default, but switch to justify-content: center for center-aligned items.
  • A perfectly centered layout may appear off if the second row has fewer items. See the difference here.
  • To keep horizontal centering intact while maintaining a left-aligned look for the last row, add a hidden flex item with visibility: hidden. For dynamic item numbers, use the selector:
    .gallery-artwork:last-of-type { visibility: hidden; }

Check out the Demo

CSS

/* Centered wrapping element */
.exhibition {
  padding: 10px;
  margin: 20px auto;
}
/* Center-aligns flex-items */   
.gallery {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.gallery-artwork {
  width: 400px;
  margin: 10px;
}
 /* Hidden filler flex-item ensures even row spacing */

.gallery-artwork:last-of-type {
  visibility: hidden;
}

HTML

<section class="exhibition">
  <div class="gallery">
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
    <div class="gallery-artwork">
      <img src="http://placehold.it/400x225">
    </div>
  </div>
</section>

Answer №4

Below is the revised CSS code you requested:

.gallery {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}

.gallery-artwork {
  width: 400px;
  display: flex;
  flex-flow: column;
  margin: 0.5em;
}

jQuery function:

$(document).ready(function(){
var count = $('.gallery-artwork').length;
    if (count % 2 == 0){
    }else{
        $(".gallery").append("<div class='gallery-artwork'></div>");
    }
});

Fiddle link: https://jsfiddle.net/debraj/p01mx39h/9/

Answer №5

Make a slight adjustment to your gallery css:

justify-content: center;

Today, I implemented this change and decided to share it immediately. I found the information on flexbox techniques very helpful on this CSS-tricks page.

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

Tips for organizing a dashboard design with Bootstrap

I am looking to design a dashboard using the Bootstrap grid system. Here is the layout I have in mind: https://i.sstatic.net/cqWP5.jpg What would be the optimal way to structure this in the HTML file? Would a layout of 5 rows and 2 columns work best? Th ...

Android WebView does not support rendering Persian fonts

I am having an issue with applying a Persian font to my html content, which contains both Persian and English text. The CSS is correctly applied except for the font itself. In the CSS, I have defined the font-face like so: @font-face{ font-family ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...

Expanding Grid Container in Material UI to Fill Parent Height and Width

Challenge I'm struggling to figure out how to make a Grid container element expand to the height and width of its parent element without directly setting the dimensions using inline styles or utilizing the makeStyles/useStyles hook for styling. I&ap ...

Issues with CSS Min-Height in Various Web Browsers

Lately, I've been working on a website and trying to create a border that surrounds all my content and extends the full length of the page. The #Container div is supposed to expand to fill the entire page. I've tried using min-height:100%; in my ...

Struggle with creating a responsive Strava Iframe (CSS/HTML)

UPDATE: My ongoing attempts to make the iframe container responsive have been focused on adjusting its size based on the intrinsic ratio of the iframe. Unfortunately, this approach has not fully worked as some elements of the iframe remain fixed in pla ...

On mobile devices, a height of 100vh exceeds the visible screen area

Struggling to cover the entire visible part of the browser window using 100vh due to issues on certain devices and mobile browsers. For example, in Safari, the URL section hides a top part, and similarly on some Android devices using Chrome. https://i.stac ...

Tips for showing the data from a JSON object with numerous arrays in Angular HTML

I managed to create a JSON object by parsing CSV file fields using the papa Parse library. Now, my goal is to showcase this data on an HTML page. However, I'm struggling with how to extract the arrays from the JSON object and transfer them into a vari ...

Is it possible to have a hidden div box within a WordPress post that is only visible to the author of the

How can I create a div box with "id=secret" inside a post that is only visible to the author of the post? I initially made it for the admin, but now I want the id to be visible exclusively to the post's author. For instance: If the author is curren ...

Creating a stylish dotted line separator or infill using CSS

I am currently working on developing a restaurant's website. I have been tasked with incorporating a dotted line infill between each menu item and its corresponding price. Despite spending a considerable amount of time searching online and testing dif ...

Is there a way for me to identify the vertical gaps in my code using JavaScript?

Within this specific HTML document, there are multiple div elements that have an absolute positioning applied to them I am looking to develop a JavaScript code that can determine the row of each individual div. I define a row as any space on the vertical ...

Employing a pair of images for submission in a form

Similar Question: How to change an input button image using CSS? Can I create a form with two image submit buttons? I am working on a language selection page that displays two flags (.png's) and I would like it so that when a user clicks on a fl ...

The integration of Angular CLI with SCSS is no longer a separate process -

It seems like I might be overlooking something very straightforward here. After a fresh installation of angular-cli, I created a new website with SCSS. I input the SCSS in the global style.scss as well as some in a component SCSS file. However, when I se ...

"Implementation of Google+ button causing the appearance of a horizontal scrollbar

Adding Facebook and Twitter sharing buttons was easy, but now I'm having trouble with Google+. No matter where I place the code on my page (using a Bootstrap grid), it always adds 2-3 pixels on the right side, creating a horizontal scrollbar: <div ...

Showing data from a JavaScript controller's JSON response in an HTML table

I'm currently developing a spring app using AngularJS and I have a response coming from a JS controller. My goal is to showcase this response in a table on the webpage. The object devDebtTable is accessible to the page from the JS controller. The JS ...

Consistency in table cell formatting

What is the best way to ensure all my table cells have a consistent height and width, regardless of their content? I am working on a crossword puzzle game where some cells are empty, some contain letters as the user fills in words, and others display butt ...

Tips for organizing a Bootstrap layout with a vertically centered single column alongside a 4x4 grid

I am currently in the process of familiarizing myself with Bootstrap, and I have a question about arranging the grid layout more flexibly. My goal is to center a single div vertically on the left side of the page, while having a 4x4 grid displayed on the r ...

The navigation bar is positioned at the forefront, blocking any elements from being displayed beneath it

I just started using Bootstrap and I'm facing an issue with my navbar. No matter what I do, anything I place goes behind it. Even with margins and the native padding from Bootstrap, I can't get the distance right because the div that I want to mo ...

Adjusting the parent with CSS transitions to perfectly align with the final height of a

Jade example div.parent div.child1 div.child2 Upon initial load, Child1 is visible. Clicking will hide Child1 and make Child2 visible. Another click will reverse this action. During the transition between hiding and showing the children, there s ...

Developing an HTML table using information from JSON dataset

I am working with an HTML file that includes the following code snippet: <div> <table id="apps"></table> </div> Recently, I started receiving JSON data structured like this: { "1": [ { "A": "", ...