Is it possible to horizontally center an auto-fill grid using only CSS?

I would like to fill my page horizontally with as many blocks as possible and center the result.

My goal is to have a grid that can resize when the window size changes:

wide window
xxx

small window
xx
x

Is it possible to achieve this without using JavaScript?

.box {
      box-sizing: border-box;
  
      width: 200px;
      height: 150px;
  
      background-color: white;
      border: solid 6px red;
    }

    .box:nth-child(2) {
      background-color: blue
    }

    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, 200px);
    }
<div class="center">
      <div class="grid">
        <div class="box"></div>
        <div class="box"></div>
        <div class="box"></div>
      </div>
    </div>

To visually explain the desired centering effect:

Can the yellow highlighted area be evenly distributed on either side?


The desired alignment of boxes:

Answer №1

Issue Specific to Chrome Browser


For the auto-fit and auto-fill functionalities to work properly, a known width is necessary for calculation. This can be achieved by using max-width:100% instead of width to ensure proper centering without stretching or fixed widths.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  max-width: 100%;
}

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>


Note that if the initial viewport is wide and then resized smaller, the grid may not remain centered due to issues with auto-fill.

In cases where there are fewer elements than the container can fit columns due to auto-fill, uneven spacing may occur. Using auto-fit ensures even distribution when an element is missing.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100%;
}

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>


To address spacing inconsistencies upon resizing due to relative units in max-width calculations, triggering a recalculation through animation can solve this issue.

Solution Specifically for Chrome Browser

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100%;
  animation: recalc 5s linear infinite;
}

@keyframes recalc {
  to {
    max-width: 99.9%;
  }
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>


To ensure compatibility with Firefox and other browsers, consider using viewport units for defining widths.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100vw;
  margin:0 auto;
}

.center {
  display: flex;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Answer №2

Utilize flexbox for this solution.

.box {
  box-sizing: border-box;
  
  width: 200px;
  height: 150px;
  
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (max-width: 767px) {
 .grid {
   flex-wrap: wrap;
   justify-content: center;
 }
 .box {
  width: 50%
 }
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Answer №3

Achieving center alignment for an auto-fill grid with left-aligned items is possible, even in Firefox.

To achieve this, simply add justify-content: center; to the grid container, resulting in the following code:

An illustrative example and explanation can be found on the MDN documentation page for justify-content

Your implementation would resemble the following:

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  justify-content: center; /* <-- This is all you need to add */
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

It's important to note that when there is only one row of boxes, they may not be perfectly centered, as the repeat function generates empty columns to fill the row, resulting in a slight left alignment of the actual boxes:

Answer №4

I suggest utilizing flex instead of grid in this scenario:

*{
  box-sizing:border-box; padding:0; margin:0; font-size:0;
}
html,body{
  width:100%; height:100%; background:#ccc;
}
.box{  
  width:200px; height:150px; background-color:white; border:6px solid red;
}
.box:nth-child(2n+2) {
  background-color:blue;
}
.center,.grid{
  display:flex; align-items:center; justify-content:center; height:100%;
}
.grid{
  min-width:600px; flex-wrap:wrap; align-items:center;
}
<div class='center'>
  <div class='grid'>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
  </div>
</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

How can I design a search box similar to the one on the android.com website?

Is it possible to replicate the search box effect on the Android website, where the menu items fade out and the search box expands upon clicking the search icon?view image here See the difference before and after clicking the search icon ...

The jQuery datatable offers a convenient date function that allows for date manipulation in milliseconds format

Recently, I have been working on updating the task owner ID using a lookup field selection in my code. The tasks are displayed based on the selected date from a datepicker value under the query in the controller. However, I encountered an issue where the a ...

Tips for showing just one table data cell (<td>) with identical class:

I'm facing a challenge with jQuery, HTML, and CSS. I'm currently in the process of designing a website for a railway company. The Home page is completed, but I've hit a roadblock on the tickets page. Using just HTML, CSS, and jQuery to build ...

Retrieving Data from a Promise - { AsyncStorage } React-Native

Currently, I am grappling with figuring out how to retrieve the outcome of a promise. My journey led me to delve into the React Native documentation on AsyncStorage available here: https://facebook.github.io/react-native/docs/asyncstorage I decided to uti ...

What steps can be taken to confirm that a comment posted on a specific post is genuine and related to that post?

Currently, I am immersed in the world of AJAX, PHP, and MySQL. Below is a snippet of my PHP code: if(isset($_GET['postTextComment'])){ // The text of the comment $htpc = htmlspecialchars($_GET['postTextComment']); // ID of ...

Running a React application through a personalized Express server, all the while ensuring seamless automatic updates throughout the development

I currently have a React application along with a completely distinct Express server application. To serve my React app using a customized express server, I utilize the following code within my Express app: app.get("*", (req, res) => { res. ...

Apply CSS3 attributes in real time

The for loop I have is functioning properly: <div id="page1div"></div> <script> list = " "; for (var i = 0 ; i < length ; i++) { list = "<h1 class='entriesdisplayed'>" + item(i) + ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

What is the best way to center these icons vertically in my navigation menu using CSS?

My website has a navigation menu with third-party icon libraries (Material/FontAwesome) in use. I am facing an issue where the icons are not aligning vertically with the anchor text. Adjusting the font size of the icon to match the text results in it appe ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Storing HTML in a Database

I've encountered an issue while attempting to parse through an HTML file that consists solely of tags. I wrote a function to extract the content between these tags, and while I'm able to display it on the page without any problems, inserting th ...

Conceal the information within a table using angular js and HTML

Just starting out with angular and I have a table that displays angular data directly in the HTML without any controller or model. <table width="98%" border="0" cellspacing="1" cellpadding="2" class="labels" align="center" id="locc"> <tr style ...

Issues with aligning text in TextBoxes

I'm struggling to center align my text boxes and write labels on either side. I want it to look like this: https://i.stack.imgur.com/6QsNv.png Despite trying different solutions, I can't seem to get the boxes to align in the center. Is there a ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

What is the best way to refresh a React ES6 component following an AJAX response?

I'm a beginner in React and ES6, trying to create a search field that fetches data as the user types. I want to make an AJAX call using the fetch API when the user types at least 3 characters in the field. When I run the fetch snippet code in the brow ...

Emulate a Click Using Pure JavaScript

I am looking to add a click event to my custom dropdown, which replaces a SELECT element. The purpose of this click event is to trigger the corresponding OPTION item when an LI element is clicked. It seems like Woocommerce uses some JavaScript or PHP func ...

Displaying information stored in a database as notifications in the notification icon within the HTML/PHP header

Within my MySQL database, there exists a table named order_detail. This table is populated with values from my android app. I am looking to display the order_id as a notification in my admin panel, which is built using HTML/PHP. The attributes of the orde ...

Creating visually appealing Jquery-ui tab designs

Trying to customize the jquery tabs, I experimented with styling them to my liking. One thing I did was attempt to reduce the size of the tabs by adding a height:45px; to the UI stylesheet shown below. .ui-tabs-vertical .ui-tabs-nav li { clear: left; ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...

How can the height of div1 be made equal to the container and div2 without using JavaScript?

Here is the structure of the HTML: <div id="container"> <div id="blue-box"> </div> <div id="red-box"> </div> </div> The CSS styling for these elements is as follows: #container { background-color:blue; ...