Tips for creating a dynamic grid layout with a maximum width for desktop items

Imagine this scenario (feel free to copy and paste the code into a new document for better visualization):

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

.item {
  background-color: #bfe0f5;
  height: 300px;
  cursor: pointer;
}

.separation {
  margin: 100px 0;
}
<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="separation"></div>

<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
</div>

The initial grid functions perfectly. As the window size changes, the columns adjust accordingly.

However, when there are only one or two items in the grid on desktop devices, I want them to be constrained to a maximum width.

Here's how it should appear on desktop:

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

On mobile screens, due to limited space, there would likely be one item per row with a larger size than 300px to fill up the available space.

The code above is almost flawless except for cases where there are only one or two items on a desktop screen. Is there a way to modify the code to account for this situation? These specific items should adhere to a max width.

I attempted setting the max-width property on the items and then disabling it in a media query for mobile screens. However, this resulted in the entire row being clickable despite the specified max width being only 300px.

Answer №1

Consider using auto-fill in place of auto-fit when defining the grid-template-columns.

auto-fill works by filling the row with as many columns as possible, creating implicit columns whenever necessary to fill the available space. The added columns may be empty, but they will still occupy a designated space in the row.

auto-fit, on the other hand, fits the currently available columns into the space by expanding them to take up any extra space. This happens after filling the extra space with additional columns (as done with auto-fill) and collapsing any empty ones.

source

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

.item {
  background-color: #bfe0f5;
  height: 300px;
  cursor: pointer;
}

.separation {
  margin: 100px 0;
}
<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="separation"></div>

<div class="grid">
  <div class="item"></div>
  <div class="item"></div>
</div>

Answer №2

To ensure proper layout, it is recommended to define the max-width on the grid container rather than on the individual items. For your current scenario,

.grid {
    max-width: 620px;
}

should work effectively, taking into account the calculation of (2 * 300px + 20px for the gap).

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 on concealing JavaScript values from being detected during web inspection

I need to securely pass a secret code from my backend to the front end and store it in my JavaScript script. Here is an example of how I want to achieve this: <script> var code = '<%= code %>' </script> Once the us ...

Using the prompt command in HTML is not supported

I am having trouble with incorporating the javascript prompt command into my HTML website. I need some assistance in identifying where I went wrong: <head> <script type="javascript"> var pass=prompt("What is the password") ...

Incorporating keyboard input capability to a div using jquery

I want to create a keypress listener that will only respond to the letter 'a'. When the 'a' key is pressed, I want the background color to change to transparent white and the border to become slightly grey. Here's my code, but for ...

Viewing information from a particular database table without relying on identifiers and the objects.all() method

On the profile page, I am looking to showcase various field values from the member table such as fullname, email, contactno, and companyname within the fieldset. In the models.py file for the member table: class Member(models.Model): fullname=models.Ch ...

What is the best way to download an updated social media post for a Django user?

Objective A user has the ability to edit their own posts by clicking on the edit button, making edits, and then saving the changes. Issue Editing a social media post does not result in the changes being saved. Overview Create a new post similar to how ...

Reposition icons accordingly while incorporating a new set of icons

After creating a new icon set font, I noticed that the icons are not positioning correctly and appear smaller than expected when loaded: https://i.stack.imgur.com/1OsAL.png https://i.stack.imgur.com/zmLQq.png I attempted to adjust the .icon class by add ...

What is the best way to address the problem of quotes while utilizing Freemarker in conjunction with ckEditor (or any other html editor

Consider this scenario within my template: ${(object.attribute)!"default text"} At times, quotation marks are necessary, such as when FreeMarker is handling null dates and similar instances. The issue arises when my HTML editor automatically transforms ...

Steps for binding the chosen item in Syncfusion SfListView

I've encountered an issue with my razor file: @using Syncfusion.Blazor.Lists; @inject NavigationManager NavigationManager @page "/main_list" <h1>Select the items</h1> <SfListView DataSource="@ShopItems01.ToList()" ...

Using AngularJS, a single controller is shared between two different views, but the scope is failing to load

I have a website where users can shop online. I want to make it so that when a user removes a product from their shopping cart, the specific sections on the page reload automatically. On my index page, there is a list of products displayed using ng-repeat, ...

Sharing data between parent and child components in React

I am facing an issue with passing a dynamically generated value from child components to my parent/web component. The buttons in the child component are assigned a `value="URL"` based on MongoDB data, and I want to pass that value to my parent component us ...

Incorporate JSON data to display SVG images

As a beginner in web development, I have been honing my skills with the AngularJS framework due to its user-friendly nature. Currently, I'm working on pulling JSON data from an API using $http.get method. One of the fields contains an image source i ...

Clean up your CSS code in Firefox 10.0.X with this amazing cleaner

Searching for a tool to clean up CSS in Firefox 10.0.x similar to Dust-Me Selectors. Unfortunately, Dust-Me Selectors is currently not supported in Firefox 10.0.x. Any recommendations for an online tool to identify unused CSS selectors? ...

Incorporate a tooltip into a horizontal bar chart created using D3

Having trouble adding a tooltip popup to display the year and value when hovering over the bar. Tried multiple options without success. Any suggestions? Experimented with a similar approach as shown in this link but still facing issues, especially with th ...

Removing values when disabling a button using JavaScript

Within my code, I have two tables - one for non-clickable teams and another for clickable matches. Check out the image of the tables View the code on my GitHub repository let teams = [ {name: 'Roma', points: 0, wins: 0, draws: 0, loses: ...

What is the correct CSS2 selector syntax to apply the :hover effect to the nth child of a specific element?

My goal is to apply a unique background color to each menu li element when hovered over, and I want to accomplish this using CSS2. <ul> <li> <li> <li> <li> </ul> I managed to add a background color to t ...

Center alignment of text and images within the button's image

Can someone help me format my CSS properly? I have a button image where the text should be on the left side and another image on the right side. Currently, everything is centered. Thank you in advance. Here is the current code: button { /* padding- ...

How do I initiate PUT and DELETE requests from my HTML code?

I am currently in the process of developing a web application that will manage items within a list. Previously, I used buttons with event listeners and JavaScript functions to handle editing and deleting items. However, I am now transitioning towards build ...

What is causing the element to automatically default to the maximum width setting?

While developing a chat app, I encountered an issue with CSS styling. I assigned a specific class to incoming messages and set a max-width limit for the container element. However, instead of the width adjusting based on the content within it, the message ...

Inconsistency with Mobile Viewport Problem

Apologies for the chaos below, but I've spent quite some time attempting to fix this on my own. It's time to surrender and seek assistance! Here are some screenshots to illustrate the issue: The problem is that sometimes the webpage functions c ...

Displaying only the Active field in tabs in Bootstrap Django

I have a question about two tabs: Active Projects Inactive Projects The application model has a field called {{app.is_active}}. Would using a script to filter the tabs be the best way to display "Active projects" in the active tab and ...