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

Troubleshooting textarea resize events in Angular 6

In the development of my Angular 6 application, I have encountered an issue with a textarea element. When an error occurs, an asterisk should be displayed next to the textarea in the top-right corner. However, there is a gap between the textarea and the as ...

The text is exceeding the boundaries of its container, displaying in a single line that extends beyond the page

I am currently working on incorporating text into the project-details section by utilizing a rich text uploading field in Django admin. Despite inputting the text as a paragraph in the Django admin project description, it displays as a single line that ove ...

Expanding div that adjusts to content size and expands to fit entire page

Appreciate your help. I'm currently facing an issue with the "content" and "footer" sections within the "wrapper" element. Below are the styles for these elements: #content { width: 100%; min-height: 100%; position: relative; background- ...

Adjust the text size of Twitter Bootstrap on mobile screens

I recently started using Twitter Bootstrap. I am currently hiding certain <tr> elements on phone screens by utilizing the class="hidden-phone". However, I am now looking to resize the displayed text to better fit the screen. Is there a way to adjus ...

Dynamic WordPress Website Designs

Seeking recommendations for responsive WordPress themes that offer extensive CSS and structural customization options. The goal is to retain all of WordPress's built-in features, such as blogging capabilities, while having the freedom to completely co ...

Converting the OpenCV GetPerspectiveTransform Matrix to a CSS Matrix: A Step-by-Step Guide

In my Python Open-CV project, I am using a matrix obtained from the library: M = cv2.getPerspectiveTransform(source_points, points) However, this matrix is quite different from the CSS Transform Matrix. Even though they have similar shapes, it seems that ...

Creating a form with an input field and an image side by side in HTML

I've been attempting to display an HTML input element and an SVG image on the same line without success. I've tried various solutions from stackoverflow, but none seem to work for me. Here's my current HTML code: <div id = "inline_eleme ...

Is there a way to alter the styling of a React element without resorting to querySelector?

Just diving into React and I'm faced with a challenge - how to update the CSS of a class based on a condition. let customizeColumn = document.querySelector(".main-table-body"); !expandFilter ? customizeColumn.setAttribute("style", ...

How to customize JavaFx context menu appearance using CSS to achieve a full-width background color

I am trying to customize my context menu, but I'm having trouble with the white space between the menu item and the context menu border. Here is an example: view the rendered context menu with CSS styles What I want is for the color to fill the entir ...

Creating customized JQuery UI tabs to perfectly accommodate the available horizontal space

Can JQuery UI Tabs be modified to fill the horizontal space and stack to the left? In order to achieve this, could we consider using a markup like the one below: <table width="100%"> <tr> <td> ...content... </td> ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...

Exploring the use of the map function for iterating in a stepper component of

I've been attempting to integrate Redux Form into my stepper component. However, I'm facing an issue where adding form fields results in them being displayed in all three sections. To address this, I started reviewing the code for the stepper. I ...

Tips for choosing and deselecting data using jQuery

Is there a way to toggle the selection of data in my code? Currently, when I click on the data it gets selected and a tick image appears. However, I want it so that when I click again on the same data, the tick will disappear. How can I achieve this func ...

The process of combining a CssStyleCollection with a System.Web.UI.WebControls.Style

I am working with a list item and trying to apply styles using System.Web.UI.WebControls.Style. However, I noticed that there isn't a MergeStyle option similar to what's available for controls. Instead, there is an Attributes.CssStyle property of ...

Having trouble with the focusout() function not registering on the search box?

When using the focusout function, I encountered an issue where clicking on a title in the search results would prevent redirecting to the title page. Although the function worked properly when closing the search results by clicking on a different element o ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...

Mobile-responsive iFrame content is designed to adjust and fit appropriately on

While my iframe is responsive on both mobile and website, I am facing an issue where the content overflows (both overflow X and Y) from the width and height of the iFrame. Here's the scenario: in the mobile view (simulated using Google Chrome to mimi ...

Issue with ChartJs version 2.8.0: The custom tooltip remains visible even when clicking outside the chart canvas or moving the mouse pointer

I am utilizing ChartJs to display a line chart with a custom tooltip that appears upon the click event of the data points. The challenge I am facing is that the custom tooltip remains visible even when the mouse pointer is outside the chart canvas area. ...

To showcase the entire contents of a specific column from one table onto a different table on the following page once the box is ticked

Everything seems to be running smoothly, except for one issue. When a row contains the value "hello world" in a column on the first page, it only displays "hello" in the item column on the second page. I'd like it to show the full value "hello world" ...