What is the best way to create a flexible grid that automatically adjusts to either two columns or one column depending on the width of the

My challenge lies in arranging items into two columns or one, with a specific layout for mobile devices.

The order of the items changes between the two column and single column layouts.

The number and size of items vary dynamically.

For example, in a two-column display:

left.one right.one
left.two right.two
left.three

Due to varying item heights, left.two may not align perfectly with right.two...

In a single column, it might look like this:

left.one 
left.two 
right.one
right.two
left.three

I need to assign classes dynamically based on whether the items are displayed in one or two columns.

How can I create a flexible grid structure without needing to conditionally wrap column content (such as div.left and div.right) when in two-column view? I want to avoid relying on JavaScript for this solution. Can it be achieved using just CSS?

I won't share my current JavaScript-dependent workaround that wraps each column's content because I'm looking for a pure CSS solution.

Please note, this is a demonstration and does not serve as the final answer to the problem at hand.

:root {
  --gridColumns: 2;
}

.left,
.right {
  padding: 10px;
  margin: 10px;
  color: white;
  background-color: grey;
  border-radius: 2px;
}

.grid {
  display: grid;
  background-color: lightgrey;
  grid-template-columns: repeat(var(--gridColumns), 1fr);
}

@media screen and (max-width: 400px) {
  :root {
    --gridColumns: 1;
  }

}
<div class="grid">
  <div class="left one">left one</div>
  <div class="right one">right one</div>
  <div class="left two">left two</div>
  <div class="right two">right two</div>
  <div class="left three">left three</div>
</div>

Answer №1

Here's a different approach that involves reordering the grid-items in the original layout.

:root {
  /* Utilizing CSS Custom properties ('CSS Variables') for easier presentation updates: */
  --gridColumns: 2;
}

.left,
.right {
  padding: 10px;
  margin: 10px;
  color: white;
  background-color: grey;
  border-radius: 2px;
}

.grid {
  display: grid;
  background-color: lightgrey;
  /* Using the custom property defined earlier to set the number and size of grid columns dynamically: */
  grid-template-columns: repeat(var(--gridColumns), 1fr);
}

/* Responsive design using CSS media queries to adjust grid columns on smaller screens (<400px): */
@media screen and (max-width: 400px) {
   :root {
    --gridColumns: 1;
  }
}
/* For screens wider than 400px: */
@media screen and (min-width: 400px) {
  .grid {
    grid-auto-flow: dense; /* Avoiding empty cells with 'dense' grid auto flow */
  }
  .left {
    grid-column: 1; /* Placing elements with 'left' class in first column */
  }
  .right {
    grid-column: 2; /* Placing elements with 'right' class in second column */
  }
}
<div class="grid">
  <div class="left one">left one</div>
  <div class="left two">left two</div>
  <div class="right one">right one</div>
  <div class="right two">right two</div>
  <div class="left three">left three</div>
</div>

Check out the JS Fiddle demo here.

For more information, refer to:

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

Exploring the potential of utilizing the "wait" function in Selenium WebDriver for

I want to automate a test on my website using the Selenium WebDriver for JavaScript. How can I approach running tests here with content that may not be ready when the page loads, such as data coming from an external API? In my case, the content is loaded ...

What is the best DOCTYPE declaration to implement?

After exploring various resources on DOCTYPE declaration and its variations - strict, transitional, and frameset, I am still struggling to grasp their distinctions. The specific confusion lies in understanding the variance between strict and transitional d ...

Font sizes for inline elements can be customized with gaps

Having trouble with setting font-size styles for inline elements, causing unexpected gaps to appear. Despite finding related questions on this issue, I have yet to discover a solution that fits my specific case. Here is the code in question: <!docty ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

Storing data locally in PhoneGap using localStorage via AJAX calls is a common requirement for

Our mobile application is built with cordova [phonegap] and we are looking to implement offline saving of results into the cache memory. The results are fetched from a PHP server and displayed in a webview using ajax and javascript. I have tried using loc ...

What is the best way to position a button directly to the right of a text box with no space in

Is there a way to perfectly align a submit button to the right of a text or search box, matching the height of the search box, and eliminating any unwanted white space between them? This is my current setup: <input type="text" value="" placehold ...

Vertical alignment is somewhat functioning but not completely

Could someone help me figure out why my green DIV is not vertically aligned in the middle of the red DIV and suggest a solution? Thank you! Link to JSFiddle .wrapper-alt { margin-right: auto; margin-left: auto; width: 980px; display:tab ...

Looking to create a responsive image in a liquid file on Shopify

Recently, I added a new feature to my Shopify backend where users can upload images to a page. While I can see the images on the front-end, they are currently aligned to the right. My goal is to make these images responsive by default and expand to fit the ...

Preserve selected option in select box after page refresh in JSP

I'm working on a jsp page that contains a simple select html element. Right now, when I select an option and click the Wyswietl button, the page refreshes, the table data is refreshed, but the selected option resets to default... How can I make it sta ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

The div width set to 100% is not functioning properly upon the initial form loading in IE11, however, it is working

[![enter image description here][1]][1]Can anyone assist me in resolving this issue? When my Div with the id "Coverage" loads initially, its width is set to the content width. However, after a refresh, it expands to 100% width. This problem does not occu ...

Mobile version experiencing issue with Navbar not collapsing

The dropdown navigation bar on the mobile version of my website is not functioning properly. Despite several attempts, I have been unable to figure out a way to make it work effectively. <!DOCTYPE html> <html lang="en"> <head> & ...

Looking to show a div upon clicking a link with the use of Javascript

Looking for a workaround due to restrictions on using alert or any Js dialog box, I need to create some sort of magic trick: 1. Create a div with a link named "info". 2. Develop an invisible div that will serve as my "PopUp" containing random information. ...

While continuing to input text, make sure to highlight a specific element from the search results list

Currently, I am using a customized search feature in my React.js application. I am looking for a way to focus on an element within the search results so that I can navigate using arrow keys. At the same time, I need to keep the input field focused to conti ...

Some devices may start the Flutter web page zoomed in by default

Experiencing Zoom Issue on Flutter Web Project: While working on my Flutter web project, I have encountered an issue where the page loads with a zoomed-in view on certain devices. Despite setting the viewport meta tag correctly, the zoom problem persists. ...

What is the best way to distinguish elements in the same HTML using Angular Material?

Currently, I am working on a project using Angular material, where I have a component.html file that defines a form and a table with data. In the first image of my project, you can see the tab title, a form to add new records, and the table displaying exi ...

Having difficulty integrating a Hangout button using APIs on my webpage

I'm having some trouble adding a basic Hangout button component to initiate Google's Hangout. I've been following the steps outlined on the Google Developer page, but despite my efforts, I can't seem to resolve the following issue: Fai ...

Scrolling horizontally with scrollbar functionality

My goal is to create a webpage with a horizontally scrollable DIV element in the center, where the scrollbar appears only at the bottom of the DIV, not at the bottom of the entire page. I am wondering if it is possible to have a scrollbar placed at the ve ...

Display a horizontal progression indicator during the page download process

Occasionally, website pages may take a while to download without the user even realizing it. This can be problematic if the user clicks on an image or button with an event handler attached, as it may break the page functionality. To address this issue, I ...

Modify the appearance of material-ui checkbox

For my project, I am utilizing React along with the styled-component package for styling. However, I am facing an issue when it comes to styling the Material-ui checkbox using styled-component. The problem lies in narrowing the border of the checkbox, as t ...