Shifting columns in CSS Grid as the screen size changes

I'm having trouble figuring out the best way to organize my grid items on an HTML page. I have several charts, each with a previous and current version. Sometimes the heights of these charts vary, so I decided to create a layout with two columns and multiple rows. The Previous charts will be on the left and the Current charts on the right:

<div class="my-grid">
  <div class="chart previous">Previous</div>
  <div class="chart current">Current</div>
  <div class="chart previous">Previous</div>
  <div class="chart current">Current</div>
</div>

However, when the screen becomes narrow, I want all the charts to display in a single column, with the Current charts appearing before the Previous ones. I've attempted using CSS grid, but couldn't figure out how to move the charts to the front or back properly. Using grid-template-areas resulted in overlapping charts.

View the codepen example here

If you resize the view to be narrow, the blocks should rearrange so that all the orange Current blocks are at the top, followed by the blue Previous blocks, while maintaining their original order.

Below is an image depicting the desired wide view (which currently works as intended)

https://i.sstatic.net/yrnAL80wm.jpg

Narrow View:

https://i.sstatic.net/oTntvg3Am.jpg

What would be the best approach to achieve this layout using CSS grid, or any other simple CSS technique? I'm open to rearranging the items in the HTML, as long as they appear correctly in the display order.

Answer №1

To organize your items into columns, simply use grid-auto-flow: column. When the width becomes too small, switch to a single column layout and adjust the order of items using order.

Check out this example on CodePen for reference.

.grid {
  display: grid;
  gap: 16px;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: column;
}

.previous {
  grid-column: 1;
  background-color: green;
}

.current {
  grid-column: 2;
  background-color: orange;
}

.item {
  border: 1px solid black;
}

.tall {
  height: 100px;
}

@media (max-width: 600px) {
 .grid {
   grid-template-columns: 1fr;
 }

 .previous {
  grid-column: 1;
  order:1;
 }

 .current {
  grid-column: 1;
 }
}
<div class="grid">
  <div class="item previous">Previous</div>
  <div class="item current">Current</div>
  <div class="item previous tall">Previous</div>
  <div class="item current">Current</div>
  <div class="item previous">Previous</div>
  <div class="item current">Current</div>
  <div class="item previous">Previous</div>
  <div class="item current tall">Current</div>
</div>

Answer №2

Implementing CSS Order Property for Chart Arrangement

By utilizing the order property in CSS, you can easily arrange your charts by including the following code snippets.


.previous {
    background-color: green;
    order:2;
}

.current {
    background-color: orange;
    order:1;
}

This configuration will prioritize displaying the current chart before the previous one, aligning with the provided visual references.

To delve deeper into the functionality of this CSS Order Property, refer to the detailed documentation available.

Answer №3

Considering the aspect of rearranging HTML is not a concern, utilizing flexbox seems to be the ideal solution for this scenario. Paulie_D has already provided insights on how to implement it with grid. It appears more organized to have similar elements grouped together in the HTML structure.

Place all current elements within one div and previous elements within another div. Both should operate as flexboxes in column mode.

Next, wrap these two columns with a wrapper element that serves as a flexbox, set to display horizontally for desktop and vertically for mobile. The only adjustment needed between the two views is the flex-direction property on the wrapper element =)

<html>
 <head>
  <style>
   .grid {
display: flex;
gap: 16px;
   }

   .row-current, .row-previous {
display: flex;
flex-direction: column;
gap: 16px;
width: 100%;
   }

   @media (max-width: 600px) {
.grid {
    flex-direction: column;
}
   }

   .item {
border: 1px solid black;
   }

   .tall {
height: 100px;
   }

   .previous {
background-color: green;
   }

   .current {
background-color: orange;
   }
  </style>
 </head>
 <body>
  <div class="grid">
   <div class="row-current">
    <div class="item current">Current</div>
    <div class="item current">Current</div>
    <div class="item current">Current</div>
    <div class="item current tall">Current</div>
   </div>
   <div class="row-previous">
    <div class="item previous">Previous</div>
    <div class="item previous tall">Previous</div>
    <div class="item previous">Previous</div>
    <div class="item previous">Previous</div>
   </div>
  </div>
 </body>
</html>

(An added benefit is that you can target items based on their parent rather than assigning the "previous" or "current" class to each item individually, such as using .row-current > .item instead of .item.current.)

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

Transform @Html.PagedListPager from MVC into a structured list using Ul and LI elements

I'm currently using a paging code in my view. How can I convert this into "ul & li" tags? @Html.PagedListPager(Model, page => Url.Action("DisplayTTs", "TTCreator", new { page = page, SearchTT = ViewBag.searchTxt })) ...

Top suggestions for maintaining the Firefox extension popup open when clicking the navigation button

As I work on developing a Firefox extension using jetpack, I have encountered an issue. It seems that when I click on the navigation button, a popup opens but then closes automatically when I click elsewhere. Is there a way for me to override this automa ...

Animating a div to continuously move back and forth in jQuery

My goal was to have a div move continuously left and right when the page loads. However, I mistakenly made it so that the movement only occurs on click events. The code snippet below shows what I initially wrote: <script src="https://ajax.googleapi ...

The typography components within material-ui are appearing side by side on the same row

I'm having an issue with my typography components appearing on the same line instead of two separate lines. I've tried various methods to fix it but nothing seems to work. <div class="center"> <Typography variant=&q ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...

Having trouble displaying the fancybox helper buttons

I had everything working perfectly, but suddenly it stopped and I can't figure out what went wrong. I just need the left, right arrows, and helper buttons to appear when fancybox is open. Any assistance would be greatly appreciated. PS: All the neces ...

Maintaining the integrity of my flexible design as the screen resolution exceeds 960px

Hey there! Currently I am utilizing the fluid layout grid system for responsive web design. I really appreciate being able to adjust the size of elements based on screen resolution using media queries, but I have a specific request. My goal is to ensure ...

"Looking to add some flair to your website with a

I am trying to figure out how to place a 30x30px no-repeat background image in the top left corner of a 200px by 200px div, positioned 120px from the left and 50px from the top. However, I also want to ensure that the text inside the div is displayed on to ...

Unable to save file as .css in Sublime Text

I'm currently delving into the world of web development, specifically exploring CSS. However, I've encountered a perplexing issue that is preventing me from applying any styling to my webpage. Initially, I suspected that the problem lied in incor ...

Switching back regular text from a superscript in document.execCommand

Currently, I'm developing a customized text editor that utilizes a contenteditable div with some basic formatting features. To enable superscript functionality, I'm employing the command document.execCommand("superscript", false, undefi ...

When the navbar collapses, it pushes non-collapsible elements aside to make room

I'm facing an issue with my navbar design. Currently, I have a navigation bar with a toggle button that collapses the menu on smaller screens. However, I want to prevent a specific element, which I refer to as the "army of shopping carts", from collap ...

Customizing existing Mui classes through the use of makeStyles

Recently, I made a small change in my approach to styling by moving CSS directly into my component files using styled components, emotion, and make styles. This decision was driven by the benefits of easier management and improved development experience. A ...

Enclose an image with a <div> element while maintaining the <div> height at

Encountering a challenge where positioning an element on top of an image at specific coordinates (20% from the top and 30% from the left) is required. Initially, the solution involved wrapping the image in a div with a relative position and using absolute ...

Arranging shapes of traffic lights in a stack

I'm attempting a straightforward task. My goal is to design a basic traffic light using a rectangle and three circles nested within it. Despite my efforts using SVG for the shapes, I've been unable to properly align the circles on top of the rect ...

Creating Consistent Height and Alignment for Bootstrap 4 Cards

Aligning Bootstrap 4 cards using d-flex and align-self-stretch for the cards works great. But I'm struggling to make the part with the red border float to the bottom. Any suggestions using only Bootstrap 4 utilities? https://i.sstatic.net/2VUME.png ...

Easily manipulate textboxes by dynamically adding or deleting them and then sending the data to a

Can you provide a simple example of how to dynamically add and remove textboxes and then display the results? I envision it like this: [Empty Textbox][Add button] When 'Value1' is entered into the textbox and 'add' is clicked, it s ...

the new adjustment has not taken effect on index.php

I have been working on my index.php file and have included various other files as well. Let me show you the structure: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css" /> <style type= ...

Unable to submit form using the submit button

Can anyone explain why the form won't submit in this scenario? I prefer not to use input type='Submit', but the function call seems to be working. <button onclick='submitForm()'>Save</button> function submitForm() { ...

Automated scrolling effect within a container element

I am working on a div container named wrapper2 that houses a chat interface. Inside the container, there are five messages in a div called chatleft, each containing images. The height of the wrapper2 div is smaller than the combined height of all the messa ...

Troubleshooting the issue of the background of element A not changing when hovering over element B, despite mouseleave not

Currently, I am attempting to modify the background of element A when mouseover event occurs on element B, and then revert it back to its original state upon mouseleave. It's worth noting that B is nested within A. Strangely, while the background colo ...