Automatically generating new lines of grid-template-columns with CSS grid

I am new to using grid in CSS and there are still some concepts that I don't quite understand. Below is the container I am working with:

<section class="css-grid">
  <div class="css-item"><img src="1.jpg" /></div>
  <div class="css-item"><img src="2.jpg" /></div>
  <div class="css-item"><img src="3.jpg" /></div>
  <div class="css-item"><img src="4.jpg" /></div>
  <div class="css-item"><img src="5.jpg" /></div>
  <div class="css-item"><img src="6.jpg" /></div>
</section>

Accompanied by the following CSS code:

section.css-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    grid-template-rows: 1fr;
    column-gap: $gap-5px;
}

img {
    width: 100%;
    cursor: pointer;
}

Currently, this setup works perfectly for a single line of images, fitting 6 images with a minimum width of 250px or maximum available space evenly among them. However, I need to achieve a specific layout behavior when the screen size is reduced.

  • If there is only one image, it should occupy the entire width (1fr).
  • If there are two images, they should split the width equally (1fr and 1fr).
  • This pattern continues for more images in a row, maintaining an equal distribution.

I have tried adjusting the grid-template-rows: 1fr property with no success, as well as experimenting with grid-auto-columns. While I am still learning about CSS grid, these nuances escape me at the moment. Can anyone provide some guidance on this matter?

Thank you,

--

Edit - Additional Information

I apologize for any confusion in my explanation; I am struggling to articulate my thoughts clearly.

To clarify further, here is what the current layout looks like:

grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

You can view an example here.

Through media queries, I aim to adjust the layout behaviour when the screen size decreases below a certain threshold, such as 1300px. In such cases where elements do not fit within the designated width, I want them to occupy the full width and share space if necessary.

I initially believed my primary line (grid-template-columns) was sufficient but realized it wasn't. Therefore, I attempted something like:

@media screen and (max-width: 1300px) {
    grid-template-columns: 1fr;
}

However, this approach did not yield the desired outcome.

The goal is for the layout to adapt as follows:

- If there is one image, it should fill the entire width (example)

- For two images, they each take up 50% width (two images)

- When three images are displayed, they should adjust accordingly(three images)

I hope this clarifies my query slightly, though I understand it may still be unclear.

Answer №1

Below is an example of how to achieve the desired layout using flex wrap:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .css-flex {
      border: 1px solid;
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      padding: 5px;
    }
    
    .css-flex>.css-item {
      border: 1px solid;
      min-width: 250px;
      height: 200px;
      flex: 1;
    }
  </style>
</head>

<body>
  <section class="css-flex">
    <div class="css-item"></div>
    <div class="css-item"></div>
    <div class="css-item"></div>
    <div class="css-item"></div>
    <div class="css-item"></div>
    <div class="css-item"></div>
  </section>
</body>

</html>

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

Improved explanation of DOM elements in raw JavaScript

Is there a more efficient way to dynamically create this DOM block: <tr> <td>text</td> <td><input type="checkbox"></td> </tr> I have a function that adds a nested tr element to my tbody: function inse ...

Is there a requirement to download and set up any software in order to utilize Highchart?

I've been working on a project to create a program that displays highcharts, but all I'm getting is a blank page. Here's my code: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charse ...

Is there a way to adjust the placement of the h1 tag using the before pseudo-element?

I'm looking to place an image on the left side of each h1 tag. I've been attempting to utilize the before pseudo element for this task. The issue arises when there is no content, causing the before pseudo element to overlap with the h1 tag. How ...

What is the best way to align text in the center of a button?

When creating custom buttons in CSS using <button>, I noticed that the text appears to be centered both horizontally and vertically across all browsers without the need for padding, text-align, or other properties. Simply adjusting the width and heig ...

What causes my variable to show None instead of the current stock price?

I attempted to extract the stock price data from using BeautifulSoup. However, my program is not displaying the stock price and instead showing "None". How can I correctly retrieve the stock price information? My provided code snippet: from bs4 import Bea ...

Conceal and reveal content using jQuery

I'm struggling with creating a functionality to hide and show content when a user clicks on a button (checkbox). I've written some code but it's not working as expected. The issue is that the content doesn't hide when the checkbox is cl ...

What is the method to run a script within a particular div?

Here is an example of the DOM structure: <div> <button>Click me</button> <img src=#> </div> <div> <button>Click me</button> <img src=#> </div> <div> <button>Clic ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Reducing HTML content to 20 words efficiently through the use of JS and VueJS

Currently in the process of developing a news feed using VueJS and have encountered an issue with rendering the content. Unfortunately, the API I am working with does not allow for easy customization to fit my specific needs. This API provides all the cont ...

Exploring High-Density Mobile Devices with Bootstrap 3 Landscape Mode

After completing my first Bootstrap site using version 3, I noticed a display issue when viewing it on an iPhone 5 or LG G2 in landscape mode due to the pixel density. This was not a problem with the Responsive Grid system I previously used. Although I sp ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

Updating user credits through the Model::factory() method is a common practice in my workflow

I need to update the UserCredits after a purchase. For example, if a user currently has 10 credits and purchases 10 more, I want to add the purchased credits to their existing total. The goal is to increment the current credit score with the new credits ...

Ensure that images in a browser maintain their proportions without distortion on all device screens and orientations by setting their height and width to match the

I'm working on a slideshow component in React and I want the images to dynamically adjust to fit any device screen size and orientation. The goal is for the image to resize proportionally until it reaches either the top and bottom edges or left and ri ...

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Ensure that the child element maintains equal height and width measurements within a row that is distinct

Is there a way to arrange 4 items inside a flex container in a 2 X 2 grid layout while ensuring that they all have the same width and height? I've tried using flex-grow: 1;, but since the children are in different flex containers, they do not obey th ...

Manipulating toggle buttons using CSS and jQuery

Check out this jsfiddle to see my attempt at creating a toggle switch in the form of a mute button. The toggle button shows the current setting: mute or unmute When hovered over, it displays the alternative setting However, I am encountering an issue wh ...

Where can I locate HTML codes within WordPress?

Upon inspecting the page source, I came across the following code snippet; https://i.sstatic.net/R7Fw3.jpg I attempted to search within WordPress for the HTML codes that are displayed here, but unfortunately, I was unable to locate them. I couldn't ...

How can you assign a value to an HTML Input by dragging an SVG shape or canvas?

I am currently in the process of creating a user interface for setting pricing parameters. There are three categories that need to be visually represented, along with two sliders to determine suggested Buy/Sell prices. To demonstrate my progress so far, I ...

What is the best way to identify the appropriate class name for searching in Selenium?

I'm currently on a mission to find an element based on its class name. I have extracted this snippet from the page source (which I saved as a file using BeautifulSoup): <div class="flex flex-column"><div... If I attempt to pinpoin ...