Issue
I am trying to write responsive css for flex. I have used flex-direction row and column for responsive. But it is not working. So, How to show this div box as flexible for mobile and tab devices.
For mobile: Div boxes should be like one below one(vertical).
For Tab: Div boxes should be like(horizontal) over boxes it should be like next line.
Demo: https://stackblitz.com/edit/flex-box-example-e2fqif?file=src%2Fapp%2Fapp.component.css
.flex-container {
display: flex;
}
.flex-child {
flex: 1;
border: 2px solid yellow;
background-color: blueviolet;
width: 150px;
height: 150px;
}
/* For Tablet View */
@media screen and (min-device-width: 768px) and (max-device-width: 1024px) {
.flex-container {
flex-direction: row;
}
}
/* For Mobile Portrait View */
@media screen and (max-device-width: 480px) and (orientation: portrait) {
.flex-container {
flex-direction: column;
}
}
/* For Mobile Landscape View */
@media screen and (max-device-width: 640px) and (orientation: landscape) {
.flex-container {
flex-direction: row;
}
}
/* For Mobile Phones Portrait or Landscape View */
@media screen and (max-device-width: 640px) {
.flex-container {
flex-direction: row;
}
}
<div class="flex-container">
<div class="flex-child magenta">Flex Column 1</div>
<div class="flex-child green">Flex Column 2</div>
<div class="flex-child green">Flex Column 3</div>
<div class="flex-child green">Flex Column 4</div>
<div class="flex-child green">Flex Column 5</div>
<div class="flex-child green">Flex Column 6</div>
</div>
Solution
In my opinion, instead of switching flex-direction
from row
to column
using media queries, a more elegant way is to apply flex-wrap: wrap
on the .flex-container
class, and then for each .flex-child
apply flex: 0 0 1
to facilitate natural wrapping.
After that, to control how many items you want in a row, you can use the width
property within the .flex-child
class. This method allows for precise adjustment of the layout, accommodating different screen sizes.
At the end your code will look like this:
.flex-container {
display: flex;
flex-wrap: wrap;
}
.flex-child {
flex: 0 0 1;
border: 2px solid yellow;
box-sizing: border-box;
background-color: blueviolet;
width: 100%;
height: 150px;
}
@media screen and (min-width: 768px) {
.flex-child {
width: calc(100% / 6);
}
}
<div class="flex-container">
<div class="flex-child magenta">Flex Column 1</div>
<div class="flex-child green">Flex Column 2</div>
<div class="flex-child green">Flex Column 3</div>
<div class="flex-child green">Flex Column 4</div>
<div class="flex-child green">Flex Column 5</div>
<div class="flex-child green">Flex Column 6</div>
</div>
Answered By - Peca021
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.