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>