Creating a flexible layout using Flexbox

Currently, I have successfully coded a layout using Grid, but now I am looking to achieve the same layout using FlexBox due to compatibility issues with IE-11. Unfortunately, IE-11 does not support Grid properly.

Let's simplify things and focus only on xs screens. Imagine that I have 6 cards:

<div class="container">
  <div class="card1"> card 1 </div>
  <div class="card2"> card 2 </div>
  <div class="card3"> card 3 </div>
  <div class="card4"> card 4 </div>
  <div class="card5"> card 5 </div>
  <div class="card6"> card 6 </div>
</div>

I want the structure to be flexible so that I can add or remove cards dynamically, and the layout adjusts automatically based on the number of cards present.

The default size of each card should match its container's width. For instance, if there is only one card, it should occupy the full width.

<div class="container">
  <div class="card1"> card 1 </div>
</div>

If there are two cards, the width should be divided between them equally, similar to using flex-grow.

<div class="container">
  <div class="card1"> card 1 </div>
  <div class="card2"> card 2 </div>
</div>

However, I encounter an issue with flex-grow as I cannot control how the cards are stacked. In the case of having 6 cards on an xs screen, I want them to form 3 rows with 2 cards in each row, which cannot be achieved solely with flex-grow.

For medium-sized screens, I would like the cards to be displayed in 2 rows of 3 cards each. And for xs screens, the layout should consist of 3 rows with 2 cards in each row.

I understand that FlexBox is one directional, but perhaps there are tricks or tips that I am not aware of. You can view my codepen example at https://codepen.io/jamie-jamier/pen/yLewWqy. However, please note that it does not fully meet my requirements. When you resize the screen to 500px, you'll notice that the use of flex-wrap results in displaying one card per row.

Answer №1

Based on my interpretation of your needs, I have made some adjustments to your CSS code and included a media query for medium-sized screens. Please review to see if it meets your requirements.

.container {
  display: flex;
}

.card {
  flex: 1;
  height: 300px; 
}

.card1 { background-color: lemonchiffon; }
.card2 { background-color: lightblue; }
.card3 { background-color: mediumspringgreen; }
.card4 { background-color: khaki; }
.card5 { background-color: orchid; }
.card6 { background-color: darkgray; }

/* Styles for medium devices */
@media only screen and (max-width: 1000px) {
  .container {
    flex-wrap: wrap;
  }
  .card {
    flex: 1 1 33.33%;
  } 
}

/* Styles for extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
  .card {
    flex: 1 1 50%;
  } 
}
<div class="container">
  <div class="card card1"> card 1 </div>
  <div class="card card2"> card 2 </div>
  <div class="card card3"> card 3 </div>
  <div class="card card4"> card 4 </div>
  <div class="card card5"> card 5 </div>
  <div class="card card6"> card 6 </div>
</div>

Answer №2

up to this point, I struggle to come up with a solution without using JavaScript. I need something to calculate the number of elements and apply different styles based on that count, somewhat like the following:

var cards = $('.card').length;

if(cards <= 1){
  $('.card').addClass('justOne');
}else if(cards <=2){
  $('.card').addClass('twoCards');
}else{
  $('.card').addClass('moreThanTree');
}
.card { 
  height: 300px;
}

.justOne{
  width: 100%;
}

.twoCards{
  width: 50%
}

.moreThanTree{
  width: 33.333%;
}

.card1 { background-color: lemonchiffon; }
.card2 { background-color: lightblue; }
.card3 { background-color: mediumspringgreen; }
.card4 { background-color: khaki; }
.card5 { background-color: orchid; }
.card6 { background-color: darkgray; }


.container {
  display: flex;
  flex-flow: wrap
}

/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
  .container {
    flex-wrap: wrap;
  }

  .card {
    background-color: blue;
  } 
}
<div class="container" >
  <div class="card card1" > card 1 </div>
  <div class="card card2" > card 2 </div>
  <div class="card card3" > card 3 </div>
  <div class="card card4" > card 4 </div>
  <div class="card card5" > card 5 </div>
  <div class="card card6" > card 6 </div>
  <div class="card card5" > card 7 </div>
  <div class="card card6" > card 8 </div>
</div>

Take a look at this pen similar to yours (using jQuery):

https://codepen.io/francisco2016/pen/bGEZyQJ

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

Alter the size of an element's width dynamically while maintaining a predetermined width

Having a fixed width div: // CSS @media only screen .column.small-centered:last-child, .columns.small-centered:last-child { float: none; } .lesson_lt_mc_div .small-centered { margin-top: 15px; margin-bottom: 15px; width: 296px; } foundation.css:1 ...

Using jQuery to alter the class of div elements in a specific sequence

Currently, I am working on a blog layout using Bootstrap and have encountered an issue. The specific layout requirement is to have the first two divs as col-md-3 (NORMAL), followed by the next 2 divs as col-md-6 (WIDE), then repeating this pattern for the ...

Position offset for container in Bootstrap 4

Within my webpage, I have incorporated two bootstrap containers - one placed inside the header navbar and the other below it. Both containers contain text content. My goal is to shift the text within the navbar container 15px to the left for all responsive ...

"Font-face is effective in Internet Explorer but appears to have compatibility issues in Firefox particularly regarding font formats

I have downloaded a free font that comes in regular and bold variations, with the following formats: svg, eot, ttf, woff. These fonts display properly in Internet Explorer, but they are not working in Firefox. 1. I would like to understand which format is ...

I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop. $(... + '<div class="recommendations filter" id="recCards-'+ i +'">' + &apo ...

Define the hover color options within your personalized Bootstrap 4 design

Currently, I have customized Bootstrap 4.5.3 with some simple modifications. Below is the custom SCSS code I am using: $newcolor1: #00a89c; $newcolor2: #e61b53; $colors: ( "newcolor1": $newcolor1, "newcolor2": $newcolor2 ); $ ...

Hovering over graphics for automatic scrolling

I have successfully implemented a hover effect that scrolls down an image inside a div. However, I am facing an issue with making the scroll longer for images of varying lengths by using calc inside the transition property. Below is the code snippet that ...

Combining Javascript and Django for a powerful web development solution

Having trouble setting up JS on my Django web app, despite reading through the documentation and previous queries. Using the Django dev server with the following file structure: mysite/ __init__.py MySiteDB manage.py settings.py ...

The issue with background image sizing persists on Internet Explorer version 8

Here is my HTML code snippet: <div id="content_main"></div> This is the accompanying CSS for styling the content main section: #content_main { width: 1024px; height: 150px; background: url('../images/Orange.jpg'); b ...

Issues with HTML5 links not functioning as intended

I am currently working with HTML5 and have been following a tutorial which can be found here- https://www.youtube.com/watch?v=kDyJN7qQETA Below is the code snippet I have been working on- <!DOCTYPE html> <html lang="en"> <head> <met ...

The CSS and JS codes are not successfully integrating into the webpage

I am encountering an issue with loading CSS and JS files onto my page. My project involves PHP and Xampp. The file structure is as follows: My Site - CSS - index.css - JS - index.js - Index.php (Apologies for the lack of a folder tre ...

How can I make the row color of a jQuery datatable change when the row is selected?

One of my challenges involves implementing a jquery dataTable (view here) where each row contains a checkbox. I want the row's color to change when the checkbox is checked. This is the approach I attempted: <table id="tabellaOrdinaFarmaci" class=" ...

Placing a Div wrapper around the contents of two corresponding elements

I am currently attempting to wrap a div with the class name 'wrapped' around two other divs containing innerHTML of 'one' and 'two'. <div class='blk'>one</div> <div class='blk'>two</di ...

Creating a disappearing carousel on mobile and tablet that disappears when extended to md size

Currently, I am developing a website that consists of a .row with 3 columns at full size, each containing a bootstrap4 card. However, when the website is viewed on tablet or mobile devices, those 3 images should transform into a carousel display. I'm ...

Concentrating on a Div Element in React

I'm trying to set up an onKeyPress event that will be triggered when a key is pressed while a 'Level' element is displayed. I know that the div needs to be focused for events to register, but I'm not sure how to do this with functional ...

Chrome causes Bootstrap to add an additional pixel

I am currently utilizing bootstrap to design a webpage. I have divided the body into two segments: content and header. Within the content block, there is a div with the class .container .sameTable, inside of which resides another div with the classes .row ...

I am having trouble placing the button within the image

Essentially, my goal is to place the button within the image and ensure it remains in its position when transitioning to mobile mode or adjusting window size. This is the desired outcome: https://example.com/image https://example.com/button-image .img ...

An HTML table with a horizontal scroll that automatically follows the headings and a vertical scroll, but facing an issue with text

Apologies if you have seen some of my previous posts today. I created a piece of HTML that was necessary for what I wanted to achieve. I needed a horizontal scroll that would keep the thead aligned with tbody as you scrolled through the content. I also r ...

Having trouble adjusting the appearance of the dropdown menu in Angular Material's Select component

I've been attempting to adjust the style of the overlay panel within an Angular Material's MdSelect component in order to change the default max-width property of 280px. I have tried various methods, such as using '!important' to overr ...

The CSS3 Animation must come to a halt once it reaches the 75% mark

Is there a way to pause a CSS3 animation at 75% and prevent it from resetting to 0% when completed, or alternatively add a 10-second delay at 75%? Currently, the animation restarts at 0% once it reaches 100%. div { width: 100px; height: 100px; bac ...