Home > Mobile >  How to achieve multiple layouts for cards using a single grid or flex?
How to achieve multiple layouts for cards using a single grid or flex?

Time:12-03

I am trying to make a responsive card layout as shown in the image.

enter image description here

Currently what I am doing is that I am separately creating layouts for computers, tablets and mobile. then which the help of a media query I set the display property as display: none for the other two views.

For example: if I am in computer view the card layout for the computer will not have a display set as none while the other two will have a display as none.

This works but is causing a lot of redundancy. There is a way to achieve all three layouts using a flex or grid.

Please guide me.

CodePudding user response:

Flex can achieve this easily.

Depending upon the screen width you can add media queries as following, you can tweak with box width and max-width to resize the boxes.

/* tablet view */
@media only screen and (max-width: 768px){
    .parent-container {
        max-width: 320px;
    }
}


/* mobile view */
@media only screen and (max-width: 480px){
    .parent-container {
        flex-direction: column;
        align-items: center;
    }
}

You can check this out https://jsfiddle.net/rx4hvn/wbqoLe0y/35/

Hope this helps!

CodePudding user response:

You do not have to set the display: none everytime you want to design a certain design for a screen size. Media queries bring something called a breakpoint where you can specify the width (like min-width: 768px) of your screen. For mobile screen sizes just put your css under the media query with max-width: 600px. Further you can instead use the orientation property to distinguish between landscape or portrait mode.
More on Queries and screen sizes

//for mobile
    @media query and only screen(max-width: 600px) 
    {
        display:flex;
        //some more css-code
    }
    
//for tablet
    @media query and only screen(min-width: 600px) 
   {

    display: flex;
   //some more css-code

   }
   
//for desktop size
   @media query and only screen(min-width: 768px) 
  {
     display: flex;
     //some more css-Code
  }

Make sure to follow the mobile first development approach like recommended under
MDN Guide

  •  Tags:  
  • css
  • Related