Is it possible to center-align content in a grid container?

Is it possible to populate a grid starting from the center?

I am working with a CSS grid container that has dynamic content (the number of children is not fixed and gets updated regularly). Here is my current setup:

#container { 
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
}

When all four columns are filled, it looks like this:

1 2 3 4 //Numbers represent children of containers

This layout works well for me. However, I encounter an issue when there are only two divs inside the main container, resulting in the following configuration:

1 2 0 0

What I would like to achieve is the following instead:

0 1 2 0

Answer №1

UNIQUE RESPONSE:

If you are looking to work with the grid layout and have only four columns with configurations such as 0 1 0 0, 0 1 1 0, 0 1 1 1, 1 1 1 1, then you can use the following CSS:

.container {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
}

.col {
  height: 50px;
  background: green;
}

.col:first-child {
  grid-column-start: 2;
}

.col:first-child:nth-last-child(4) {
  grid-column-start: 1;
}

If your HTML structure is similar to this:

<div class="container">
  <div class="col">
  Column
  </div>
  <!-- Other Columns Here -->
</div>

You can see a live example in action on this Working Fiddle

Answer №2

It has been mentioned that Flexbox is the ideal choice for this scenario, however, a combination of specific properties can also achieve the desired result.

The following properties can be utilized:

grid-auto-flow: column;
grid-auto-columns: 25%; // assuming 4 columns
justify-content: center;
document.querySelectorAll('input')[0].onclick = () => { document.querySelector('[container]').append(document.createElement('div')) }
document.querySelectorAll('input')[1].onclick = () => { document.querySelector('[container]').innerHTML = '<div></div>'; }
body * {
  padding: 10px;
  border: 1px solid;
}

[container] {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 25%;
  justify-content: center;
}

[container]>div {
  height: 50px;
  background: orange;
}
<input type="button" value="Add Column" />
<input type="button" value="Reset" />
<div container>
  <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

Ways to conceal ad container when ad space remains empty

After setting up my ad HTML like this: <div class="ad-container"> <p>Ad slot #1</p> <div id="ad-slot-1" class="ad-slot"></div> </div> I implemented the code below to collapse the ad if ...

Looking to extract the hidden value from an HTML input field using Selenium

Unable to retrieve the value of a hidden element in HTML, even though it is displaying. Seeking assistance in accessing the value despite the type being hidden. <input type="HIDDEN" label_value="Sub Reference" title="Sub Reference" id="ACC_NO" dbt="BK_ ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

Displaying markers on a Google map by fetching data from a MySQL database in PHP

The image attached here serves as an example. You can view it here. Currently, I display locations on a map in an HTML page with static code like: Here is the JavaScript code to load the map on the page: <script type="text/javascript" src="https://ma ...

What steps can I take to resolve the TypeError issue with tailwindcss-cli where it is throwing an error stating that Object.fromEntries is

I've been diligently following tutorials by Tailwind and have encountered an error while trying to run the command npx tailwindcss-cli build css/tailwind.css -o build/tailwind.css. The error message I received is related to Object.fromEntries not bein ...

Incorporate a CSS style sheet into the app_offline file

It's been a challenge for me to create a custom app_offline.htm page and include links to my css files in the project. Unfortunately, the code snippet below doesn't seem to be working as expected: <link href="/Content/Themes/screen.css" rel=" ...

Maintain the layout of HTML page while reducing the window size

My webpage is experiencing an issue. When I resize the window, the placement of all elements becomes misaligned and the layout gets distorted. ...

Switching out images in a responsive column grid on hover using JQuery

I'm currently troubleshooting my code and would appreciate any help with debugging. The main goal is to swap out the image within the ".col" element on mouseenter and revert back to the original image on mouseleave. Additionally, I'd like to prel ...

Tips for Concealing PHP Undefined Error Messages Using Echo

I'm new to PHP and I'm attempting to display user information in a div after submission using the echo function. Here is my current code snippet: <label class="input-fields" name="cust-name"> Name <input type="text" id="cust[name]" ...

Changing the size of the Modal Panel in Ui Bootstrap for a customized look

Currently, I am in the process of developing an application that utilizes Ui bootstrap to seamlessly integrate various Bootstrap components with AngularJs. One of the key features I require is a modal panel, however, I found that the default size option &a ...

Implementing asynchronous image loading with Angular 4 using bearer headers

Currently, I am working on making asynchronous image requests with authentication headers. The image paths in the code look like this: <img src="{{file.src}}"/> I need to include a Bearer Token in the header for these requests, but since there are ...

Heroku's chat server allows for seamless communication among users

Whenever I need to run my chat server, I usually use the command ./manage.py run_chat_server. However, after deploying my app to Heroku, I am facing issues trying to run the chat_server. Can anyone provide guidance? I attempted using the console in Herok ...

Attempting to retrieve the position of an image within an array upon clicking

function displayGalleryIndex(){ console.log($(this).index()); } $("body").on( "click", "#gallery img", displayGalleryIndex); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <section class="grid- ...

The hierarchy of styles in Rails CSS/SCSS

I'm currently exploring the concept of css precedence rules in rails. In my application, I am looking to apply different css rules based on different controllers. However, when I add css to one of the css.scss files, it ends up affecting all controll ...

What is the best way to implement a partial color filter on an image using CSS?

Looking to give our business website a fresh update, but struggling with adding a filter to the images. Our graphics designer created a mock-up for us, but I'm not sure how to implement this feature. Any help would be greatly appreciated! ...

Positioning a div above a Bootstrap navbar that disappears when scrolling

I am currently using bootstrap to design a website, and I am attempting to create a div that would initially appear above the navbar on an unscrolled webpage. However, once the user starts scrolling, I want this div to disappear and have the navbar fill it ...

Example of using the CSS property white-space with break-spaces

I've been searching for an example of using css white-space: break-spaces for hours with no luck. Most tutorials only cover examples for normal, nowrap, pre, pre-wrap, pre-line. When it comes to break-spaces, the information available is limited to qu ...

Arranging two columns side by side with Bootstrap

Is it possible to align two boxes next to each other, one on the left and the other on the right? Additionally, how can I make sure that the mytitle box expands to full width on mobile devices? If floats are necessary, how can they be added when a class h ...

Hover effect on two divs changing states

I was so close to solving this issue, but I'm stuck on the final part. Here's the code snippet I've been working on: /* valuecanvas */ #wrappercs { margin-top: 3px; width: auto; height: auto; display: block; float: right; bac ...

I am in search of a clean and efficient method to modify the class of a link that triggers an HTMX request in Django. Perhaps something like "auto-refresh" or a similar solution would be ideal

I've encountered an issue with HTMX in Django. The page consists of two main components: a list of categories and the content that is displayed when a category is clicked. Initially, everything was working smoothly with standard htmx functionality. H ...