Simple layout with flexbox question:
Desktop Layout requirements
Mobile Layout requirements
What I've got so far:
When I toggle to mobile
(via button click for example on snippet below) mode I set flex-direction: column
on the flex container. It seems to work.
#flexContainer {
display: flex;
}
#flexItem1 {
background-color: lightblue;
flex: 30%;
}
#flexItem2 {
flex: 70%;
background-color: lightgreen;
}
NOTE:
This question is about which CSS flexbox properties need to be changed in order to go from Desktop Layout to Mobile Layout. It's not about how to detect the window size or how to set a media query. I'm sorry if the way I wrote it didn't make it very clear.
QUESTION
Is there a cleaner way on how to do this ?
Do I need to set the flex
property of the flexItems
to 100%
when on mobile mode or can I leave them as 30%
and 70%
as they don't seem to matter when flex-direction
is set to column
?
function App() {
const [mobile,setMobile] = React.useState(false);
return(
<React.Fragment>
<div id="flexContainer" style={mobile ? {flexDirection: 'column'} : null}>
<div id="flexItem1">Item 1</div>
<div id="flexItem2">Item 2</div>
</div>
<button onClick={()=>setMobile(prevState=>!prevState)}>Toogle</button>
</React.Fragment>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
#flexContainer {
display: flex;
}
#flexItem1 {
background-color: lightblue;
flex: 30%;
}
#flexItem2 {
flex: 70%;
background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Since you don't have any weird switch of columns from mobile to desktop, what I'd do is this (and I believe is the cleanest way)
Start thinking mobile first (mobile first IS best practice) and then use media queries for desktop version. Basically set your container to display block and set the width of both columns inside it to 100%. then on desktop, make your container flex with a query.
CSS:
#flexContainer {
display: block;
background-color: blue;
}
@media only screen and (min-width: 1024px) {
#flexContainer {
display: flex;
}
}
Or as I would do it in SCSS:
#flexContainer {
display: block;
background-color: blue;
@media only screen and (min-width: 1024px) {
display: flex;
}
}
You can use a break point with styled components.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp
https://www.styled-components.com/docs/basics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With