"Create a responsive design featuring two columns on desktop and a single column on mobile using Flexbox layout

Seeking a solution for a flexible layout using flexbox:

Requirements for Desktop Layout

  • Consist of two responsive columns
  • 1st column should occupy 30% of the width
  • 2nd column should occupy 70% of the width

Mobile Layout Specifications

  • Single column that responds to different screen sizes
  • 1st row with full width (equivalent to the 1st column on Desktop)
  • 2nd row with full width (equivalent to the 2nd column on Desktop)

Current Progress:

For toggling between mobile and desktop modes, setting flex-direction: column on the flex container seems to solve the issue.

#flexContainer {
  display: flex;
}

#flexItem1 {
  background-color: lightblue;
  flex: 30%;
}

#flexItem2 {
  flex: 70%;
  background-color: lightgreen;
}

Please Note:

This inquiry focuses on adjusting CSS flexbox properties for transitioning from Desktop to Mobile Layouts. It is not about detecting window size or media queries. My apologies if this was unclear initially.


QUESTION

Is there a more efficient approach for achieving this layout switch? Do I need to change the flex property of the flexItems to 100% in mobile mode, or can they remain as 30% and 70% since they don't impact the layout 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>

Answer №1

To maintain consistency in column display between mobile and desktop views, the best approach is to prioritize mobile design first, known as mobile-first best practice. Then, utilize media queries to adjust for the desktop version. Initially, set your container to display as a block with both columns inside having a width of 100%. For the desktop view, switch the container to a flex display using a media query.

CSS:

#flexContainer {
  display: block;
  background-color: blue;
}

@media only screen and (min-width: 1024px) {
  #flexContainer {
    display: flex;
  }
}

Alternatively, this can be implemented in SCSS:

#flexContainer {
  display: block;
  background-color: blue;

     @media only screen and (min-width: 1024px) {
        display: flex;
     }
}

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

How can I increase the size of the nuka-carousel dots in React/Nextjs?

Looking for help on customizing the size of dots in my nuka-carousel. Unsure how to change their sizing and margin. ...

How can I verify the number of completed form fields?

I seem to be facing a minor issue: I have a webpage where users can input information into up to 10 fields. However, they are not required to fill out all 10 fields. Initially, the user is presented with only one field, and they have the option to add mor ...

Search two arrays in a loop and identify variations with a unique approach

Currently, I am facing a challenge that I need assistance with. I am working on an updater that retrieves an XML list of files from a CDN and compares it with an older list to identify any file differences. The objective is to determine which files are out ...

ASP.NET DIV is experiencing issues with Jquery functionality, causing it to flicker and remain fixed in place

As a beginner in JQuery, I am facing an issue with my code in asp.net. Whenever I click on linkbuttons, the behavior is not as expected. The div flickers and does not change its direction. My goal is to move the DIV left or right by 200px, but no matter wh ...

Error: The function $.getScript(...).done cannot be found

Encountered a strange situation here.. . The following code is functioning properly: // this code working perfectly $.getScript( "https://wchat.freshchat.com/js/widget.js" ).done(( script, textStatus )=>{ // run something }); . . However, if ...

What sets justify-content apart from align-items?

I'm really struggling to grasp the distinction between these two properties. After conducting some research, it appears that justify-content can handle... space-between and space-around, while align-items is capable of... stretch, baseline, initial, a ...

Creating a versatile TypeScript interface that can accurately represent a wide range of types, interfaces, and objects whilst imposing restrictions on the allowable value types within

I am looking to define a versatile TypeScript interface that can accommodate any type, interface, or object while imposing restrictions on the types of values it contains. Let me introduce MyInterface, which includes properties fooIProp and barIProp stori ...

Encasing a drop-down menu within a personalized container

I am looking to create a custom HTML element that mimics the behavior of the native <select> element but also triggers a specific update function whenever an attribute or child node is modified. This is essential for incorporating the bootstrap-selec ...

Tips for aligning images inside tab content areas

While using an "accordion" jQuery to show a contact list, I have encountered a challenge that may seem simple to someone experienced in this. Here is the code snippet: <!doctype html> <html lang="en> ... (Code continues) I am looking to add ...

Ways to ensure this is not case sensitive

I'm struggling with incorporating .toLowerCase() in my discord command to make it case insensitive. I know it should be a simple task, but as a beginner, I find it challenging. exports.execute = async (client, message, args) => { let userBalance ...

What is the best way to connect this image and comments div using only CSS?

I'm trying to ensure the comments div is the same height as the image above so they can be aligned side by side. Below is my current code: <div class="main_image_wrapper"> <img class="main_image" src="*dynamic generated image*" style="ma ...

In Chrome, the CKEDITOR method selection.getStartElement() is returning the incorrect element

I am currently working on a main page that includes the ckeditor for text editing purposes. The elements within the ckeditor are as follows: <address>Address</address><pincode>123456</pincode> My goal is to retrieve the focused el ...

Ways to resolve a blank outcome in the $scope selection choices list?

Currently, I am utilizing AngularJS to create a select dropdown field populated with options from an array. The end user has the ability to add options via an input box. While the $scope successfully adds to the array, the dropdown select box displays "und ...

The ng-class directive in Angular is failing to function properly within the ng-repeat loop

I am facing an issue where I am attempting to color some of the items in a list using Ionic framework. The array named somearray contains the indices that need to be colored red. However, no matter what I do, only the first index in the array is being co ...

Is there a Ruby gem similar to Readability that anyone can recommend?

Readability is a nifty JavaScript tool that magically transforms a cluttered HTML page into a more user-friendly format. I'm on the hunt for a Ruby implementation or something along those lines - does anyone know of a library that offers similar funct ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

The change handler of the TS RadioGroup component, instead of returning an array of possible strings, returns a unique

My interface declaration for StopData is shown below: export interface StopData { stopName: string, stopType: 'stop' | 'waypoint' } I have implemented a radio group to choose the 'stopType', which consists of two radi ...

Shifting the position of an HTML page to one direction

I'm currently working on adding a sidebar to my Twitter Bootstrap 3 project. The goal is to have a fixed positioned nav nav-pills nav-stacked show up on the left side of the page when a button is clicked. I've set its z-index to 1000 so it appear ...

Issue "Value of type '{}' cannot be assigned to parameter of type 'T | (() => T)'" encountered within a React component containing a type parameter

Currently, I am attempting to achieve the following: function SomeComponent<T>({ children }: PropsType) { const [configuration, setConfiguration] = useState<T>({}) } However, I am encountering this issue: The argument of type '{}&apos ...

How can Mui typescript be extended with a unique wrapper that includes a `component` property?

I recently created a unique wrapper component: import Box, { BoxProps } from "@mui/material/Box"; type CustomWrapperProps = { id: string } & BoxProps const CustomWrapper = (props: CustomWrapperProps) => { const {id, children, ...rest ...