Is there a way for me to transition a grid from 4x3 to 3x4 at a specific breakpoint in the media query?

I am currently working on creating a responsive grid layout. Initially, the grid is set up as a 4x3 configuration, but once the screen width reaches 720px, I need it to convert into a 3x4 grid. The challenge is that I must accomplish this using only HTML and CSS without relying on JavaScript.

Transitioning from:

A  B  C  D
 E  F  G  H
 I  J  K  L

to... @media only screen and (min-width: 720px)

A  B  C
 D  E  F
 G  H  I
 J  K  L

I understand that rows will need to be inserted in between the elements, which is why I had previously added them dynamically using JavaScript. However, I struggled to achieve this statically with pure HTML and CSS.

function gridDivideBy(divideNum) {

  $('.myClass').contents().unwrap();
  var $square = $(".square");

  for (let i = 0; i < $square.length; i += divideNum) {
    // Create dynamic div
    let $div = $("<div/>", {
      class: 'myClass row'
    });
    // Wrap all the boxes inside a row and div with myClass
    $square.slice(i, i + divideNum).wrapAll($div);
  }
}

function myFunc(x) {
  if (x.matches) {
    gridDivideBy(4);
  } else {
    gridDivideBy(3);
  }
}


var x = window.matchMedia("(min-width: 720px)")
myFunc(x);
x.addListener(myFunc);
.square {
  flex: 1;
  padding: 5px;
  margin: 5px;
  border: 2px solid #eee;
  flex: 1;
}

.myClass {
  display: flex;
  padding: 5px;
  margin: 4px;
  border: 1px solid green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="square-wrapper">
  <div class="col-md-3 square">A</div>
  <div class="col-md-3 square">B</div>
  <div class="col-md-3 square">C</div>
  <div class="col-md-3 square">D</div>
  <div class="col-md-3 square">E</div>
  <div class="col-md-3 square">F</div>
  <div class="col-md-3 square">G</div>
  <div class="col-md-3 square">H</div>
  <div class="col-md-3 square">I</div>
  <div class="col-md-3 square">J</div>
  <div class="col-md-3 square">K</div>
  <div class="col-md-3 square">L</div>
</div>

Answer №1

If you have experience with media queries, you can easily adjust your grid layout by modifying the values of grid-template-rows and grid-template-columns.

@media screen and (max-width:720px) {
    .grid-container {
        grid-template-columns: 1fr 1fr 1fr;
        grid-template-rows: 1fr 1fr 1fr 1fr;
    }
}

Feel free to let me know if this solution works for you. Best of luck!

Answer №2

Consider exploring alternative options why?

Bootstrap 3 sets the first breakpoint at 768px

For extra small devices like phones (<768px)

However, if you insist on using Bootstrap, here's a possible solution (at least I think so...)

$(window).on("load, resize", function () {
    var viewportWidth = $(window).width();
    if (viewportWidth > 720) {
            $(".col-xs-3").removeClass("col-xs-3").addClass("col-xs-4");
    }
        else{
            $(".col-xs-4").removeClass("col-xs-4").addClass("col-xs-3");
        }
});

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

nvim-typescript incorrectly flags non-existent type errors

I am experimenting with using neovim and have set up a minimal configuration as follows: call plug#begin() Plug 'mhartington/nvim-typescript', {'do': './install.sh'} Plug 'leafgarland/typescript-vim' Plug 'He ...

What is the best way to reset an angularJS form after it has been submitted

I am trying to figure out a way to clear form fields on a modal window after the user executes the save method. I have attempted using $setPristine in AngularJS, but it's not working as expected. Any suggestions on how to achieve this task? Here is t ...

Having a problem with form submission after using preventDefault() in JQuery / Ajax?

Despite reading various questions and answers on this topic, none of the solutions have worked for me after hours of testing. Can someone please help with my problem? $(document).ready(function() { $( "#search_form" ).on('submit',function(ev ...

Saving extra parameters with MongooseJS

When saving data in my app using a POST query, how can I include additional parameters to the Item? For example, I would like to add user: req.user._id. var Item = new Model(req.body); Item.save(function (err, model) { res.send(model); }); ...

Reorder the text input element to precede the tags in bootstrap-tagsinput

Does anyone know a simple way to reposition the text input box above the tags in bootstrap-tagsinput? Check out this codepen for a visual representation: https://codepen.io/uebes/pen/KQEdeP Basically, I would like the tags to come after my input text box ...

Is it possible to partially move the image outside of the MUI dialog?

Is it possible to move an image partially outside of the MUI dialog, with the bottom part inside and the top part outside the dialog? I attempted a solution found on Stack Overflow but it did not yield the desired result. This is the dialog code: <Dial ...

Having trouble accessing the property 'TUT' because it is undefined?

After loading a JSON file using jQuery, I attempted to access specific properties but encountered an undefined error. Despite being able to clearly see the object within the JSON when printed, the issue persists. { "Calculus 1": { "LEC": { "sec ...

What are the benefits of using `observer` over `inject` when passing data to a React component in MobX?

After reading MobX documentation, it appears that using observer on all components is recommended. However, I have discovered that by utilizing the inject method, I am able to achieve more precise control over which data triggers a re-render of my componen ...

Tips on Using Firebase Database Rules to Validate a Node Property Value Against the User's Unique ID

I am currently utilizing the Firebase database and I am in the process of configuring rules to restrict write access to users whose uid matches the userId node of the object they are attempting to write, while still allowing the creation of new objects suc ...

The Java.lang.finalize heap became too large during the Hadoop URL parsing task

I'm currently working on analyzing the content of various homepage URLs by utilizing a Hadoop mapper without a reducer. This mapper fetches the URLs and sends them to a parser class for further analysis. The parser leverages Jericho's html parse ...

The font-face feature seems to be having issues on the server with the .NET application

I am having issues with @font-face not working when browsing on Safari 5.1+ from the server URL. The font displays perfectly in Safari when I view the HTML file, but when I convert it to an ASPX (.NET) file, the font appearance is not satisfactory at all. ...

How can I handle a situation in Angular where there are multiple $http requests that are interdependent and need to

Let's talk about two different URL endpoints called "fruitInfo" and "fruitDetails" The goal is to create an object with the following structure: var fruitInfoDetails = {"fruitInfo": <contents of fruitInfo response data>, "fruitDetails": <co ...

Choose Your Preferences When the Page Loads

I have a dropdown menu where I can select multiple options at once without checkboxes. When the page loads, I want all of the options to be pre-selected by default. I am aware that I can use $(document).ready() to trigger actions after the page has load ...

I am unable to store a session variable using the GET method

Good day, I am seeking assistance with my code and have been searching for four hours without finding the error. I am working on an exchange where variables are stored in a session. The issue I am facing is that the variable $discount gets cleared every ti ...

Is there a way for me to capture the text of the label that encloses my checkbox input?

Within my section-filter Vue component, the labels are populated using v-for and text from a "content" array in the data option. When a user interacts with the checkbox, I aim to retrieve both the value of "checked" (already achieved) as well as the text f ...

Step-by-Step Guide: Exporting a div to a beautifully formatted PDF with NextJs

Currently, I am working on an app project that involves filling out forms and having the information automatically formatted into a div to generate CLP labels. My goal is to be able to export this div in pdf format while also being able to select sizes ran ...

What could be causing the error 'i is not defined' in my Vue.js component script when using a basic for loop?

I have a task where I need to sort an array by version and then move all elements starting with 'ipad' to the end of the list. This code snippet is extracted from a single file Vue.js component: computed: { orderedUsers: function () { ...

The search function on my blog is not displaying the blogs that have been filtered

I have encountered an issue with my code as I am unable to get any search results from the search bar. const RecentBlogs = ({recentBlogs}) => { const [query, setQuery] = useState("") const filteredItems = (() => { if(!query) return rec ...

Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving ...

Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>: function getXhr() { var xhr = null; if(window.XMLHttpRequest) // Firefox et autres xhr = new XMLHttpRequest(); else if(window.ActiveXObject){ // I ...