Can we ensure there is consistently an even number of columns when using auto-fill?

Hello, I am just starting to explore CSS grid. Take a look at the example below:

.platform {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 20px;
}

.item {
  width:100%;
  background-color:#aaa;
  padding:10px;
  box-sizing:border-box;
  text-align:center;
}

.wrapmed {
  max-width:400px;
}

.wrapsmall {
  max-width:300px;
}
<div class="platform">
  <div class="item">a</div>
  <div class="item">b</div>
  <div class="item">c</div>
  <div class="item">d</div>
</div>

<br/><br/>

<div class="wrapmed">
  <div class="platform">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
  </div>
</div>

<br/><br/>

<div class="wrapsmall">
  <div class="platform">
    <div class="item">a</div>
    <div class="item">b</div>
    <div class="item">c</div>
    <div class="item">d</div>
  </div>
</div>

Overall, the grid setup is functioning fine. However, I want to ensure that there are never 3 items in one row and only 1 item in the next.

I aim to have either 4 columns, or two columns, or one. How can I achieve this desired layout behavior?

Update: The updated code snippet now showcases all three possible cases. Case 2 is the unwanted scenario.

Answer №1

To customize the layout of columns collapsing, you can nest the platform divs.

I introduced a parent platform element which positions two child platform elements either side-by-side or on top of each other.
Pairing items in twos inside the child platform elements offers more flexibility for arrangement.

As the screen size decreases, the child platform elements will initially stack to form a 2x2 grid.
Further shrinking causes the items within the child platforms to reorganize into a 1x4 grid.

https://i.sstatic.net/Vhx02.png

.platform {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  grid-gap: 20px;
}

.item {
  width:100%;
  background-color:#aaa;
  padding:10px;
  box-sizing:border-box;
  text-align:center;
}

.wrapmed {
  max-width:400px;
}

.wrapsmall {
  max-width:300px;
}
<div class="platform">
  <div class="platform">
    <div class="item">a</div>
    <div class="item">b</div>
  </div>
  <div class="platform">
    <div class="item">c</div>
    <div class="item">d</div>
  </div>
</div>

<br/><br/>

<div class="wrapmed">
  <div class="platform">
    <div class="platform">
      <div class="item">a</div>
      <div class="item">b</div>
    </div>
    <div class="platform">
      <div class="item">c</div>
      <div class="item">d</div>
    </div>
  </div>
</div>

<br/><br/>

<div class="wrapsmall">
  <div class="platform">
    <div class="platform">
      <div class="item">a</div>
      <div class="item">b</div>
    </div>
    <div class="platform">
      <div class="item">c</div>
      <div class="item">d</div>
    </div>
  </div>
</div>

Answer №2

Presenting a different approach for those facing the same issue, here is a solution I came up with using flexbox instead of CSS Grids. This method worked better for me as I needed my cards to collapse only in even numbers without exceeding a certain maximum width.

Unlike CSS Grids, flexbox allowed me more flexibility in controlling the width and alignment of my cards. The challenge was to prevent the cards from expanding beyond a specific width when the sub-platforms collapsed within their containers.

If there is a way to achieve this using grids, please share your insights. My attempt to set max-width on items didn't allow me to center them within grid cells while maintaining a desired minimum and maximum width.

In my solution, I implemented nested containers with varying properties, particularly adjusting the item width using the flex-basis property (flex: 1 0 50px) and setting a maximum width with max-width: 100px. This configuration allows the flexibility for items to grow between 50-100px.

.container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: space-evenly;
}

.sub-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: space-around;
  flex: 1 0 50px;
}

.item {
  flex: 1 0 50px;
  max-width: 100px;
  height: 100px;
  background-color: #aaa;
  padding: 10px;
  text-align: center;
}
<div class="container">
  <div class="sub-container">
      <div class="item">a</div>
      <div class="item">b</div>
  </div>
  <div class="sub-container">
      <div class="item">c</div>
      <div class="item">d</div>
  </div>
</div>

Answer №3

To style every other item in a list, you can utilize the pseudo-classes :nth-child(even) or :nth-child(odd)

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

Issue with Tailwind CSS: The 'overflow-y' property does not scroll all the way to the bottom when using 'top-[63px]'

I'm facing an issue with my Tailwind CSS code that is hindering me from scrolling to the bottom of an aside element. <body> <div> <nav class=" bg-white px-2 py-2.5 dark:bg-gray-800 sm:px-4 fixed w-full z-20 border-b borde ...

What are the steps for utilizing CSS Global Variables?

Hey there, thank you for taking the time to help me out. I'm having a simple doubt that I just can't seem to figure out. So... here's my '/pages/_app.js' file: import '../public/styles/global.css'; export default funct ...

Is it possible to scale images dynamically using CSS without losing their proper proportions?

http://jsfiddle.net/CJzCA/ Is there a way to resize images using CSS in the above jsfiddle? The keyboard images are currently too big compared to the text, and I usually solve this issue by using Photoshop. It would be more convenient if we could resize t ...

My website experiencing issues due to Firefox 23.0.1 altering the CSS and causing disruptions

After setting up a test site for a client to review as part of a proof of concept, I noticed an unexpected white line while checking across different browsers. (loading correctly in all browsers except FF) In Firefox, there appears to be a thin ~10px li ...

Dynamically align text in the center of an image, vertically

I'm trying to create a hover effect where an image and text are displayed in the center of the image when someone hovers over it. Here is how the HTML looks: <article> <div class="entry-content"> <a href="http://www.linktopost.com"> ...

Tips for creating a new line in PHP when the value includes a comma

I am struggling to format information that includes commas into new lines. The current output I have is shown in the current display. I would like to display it with each comma creating a new line automatically. Below is my current code: <tr> <td ...

Accessing a variable from another HTML using JavaScript

I'm currently attempting to access a variable from another HTML file using JS. Specifically, I have a file (file1.htm) that opens a dialog box, and I want to send the information of the selected file to another file (file2.htm) in order to modify a v ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Incorporate a local asciinema file into an HTML document

Is there a way to embed a local asciinema session into an html file? Here is how my directory is structured: $ tree . ├── asciinema │ └── demo.cast ├── css │ └── asciinema-player.css ├── index.html ├── js │ ...

Code to execute function depending on the width of a div

Looking for a script that can run a function depending on the width of a div. I want the ability to trigger the function when the div is resized. For example, if the div's width is 300px, execute function 1; if it's 700px, execute another functi ...

Visual Composer in WordPress is not displaying as expected

I've attempted to uninstall and reinstall Visual Composer, but I'm unable to resolve the issue. I can't edit the front end because it's not displaying properly. I'm using the Ken theme. When checking the console, I encountered this ...

What are some strategies to stop text from causing the container height of the <li> element to expand?

Link to my code on Plunker In my attempt to create a fluid layout, the sidebar of my site consists of a list of links. I am trying to make each <li> element a perfect square, but when I add text inside, it disrupts the dimensions and turns the squar ...

The selection button's threshold

Welcome to my website design project! I have implemented image buttons for my web page and want to restrict the number of images a user can select. If a user tries to navigate away after selecting more than 3 images, I wish to display an alert message. Her ...

What is the best way to delete a table that I created through my programming?

I have utilized the following code to create a table: <html> <head> <title>Table Time</title> </head> <body> <table border="1px"> <tr> ...

What is the best way to optimize Bootstrap 5 grids for mobile responsiveness?

Within my portfolio, I have a projects section that switches between having the description on the left with an image on the right and vice versa. Despite my efforts to make it responsive, I'm struggling to figure out how to ensure the image appears a ...

Guide to connecting a different HTML page to a thumbnail image using jQuery

let newColumnBlock = $('<div class="col-md-2">'); let newImagePoster = $('<img>'); let newSelectButton = $('<a href="secondPage.html"><button class="selectButton"></button></a>'); let movie ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

What is the best method for selecting an Iframe in Firefox using HTML?

As a student working on building a website, I recently added some iframes to a WordPress page and noticed that all links were opening in new tabs specifically in Firefox. The HTML code in question: <a href="http://example" target="exampl ...

Detect when a user's mouse is hovering over an iframe and escape the iframe accordingly

When the iframe window is visible, there are no issues. However, if the iframe window is set to 0px X 0px in order to hide it while still loading, consider redirecting the iframe or not displaying it at all. In case something is loaded within an iframe or ...

Heroku: Showcasing a unique page during the application's startup process

Would it be feasible to showcase a static HTML page while the dyno is starting up, just like how a custom page can be shown during errors or maintenance mode? The size of my app's slug is quite significant, leading to a startup time of almost 50 seco ...