Is there a way to specifically dictate the order in which flexbox items expand or contract?

I am facing an issue with my flex container setup involving three children elements. I have specified both minimum and maximum widths for each child, but I want them to grow or shrink in a specific order as the window width changes. Ideally, Item1 should shrink to its min width first, followed by Item2 shrinking to its min width, and finally Item3 adjusting accordingly. Can anyone guide me on what I might be doing incorrectly? I have reviewed the documentation multiple times but I still can't seem to grasp the solution.

<div className="MainContainer">
  <div className="Item1">
    I should shrink first/expand last!
  </div>
  <div className="Item2">
    I should shrink & expand second!
  </div>
  <div className="Item3">
    I should shrink last/expand first!
  </div>
</div>

Below is the CSS code I'm using:

.MainContainer {
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding-left: 15px;
  padding-right: 15px;
}
//Should shrink first/expand last
.Item1{
  min-width: 350px;
  max-width: 816px;
  flex: 1;
  flex-grow: 0;
}
//Should shrink/expand second
.Item2{
  max-width: 816px;
  flex: 1;
  flex-grow: 1;
}
//Should shrink last/expand first
.Item3{
  min-width: 300px;
  max-width: 224px;
  flex: 1;
  flex-grow: 2;
}

Answer №1

After finding inspiration from a helpful Stack Overflow post, I managed to reach my desired outcome.

I have made some adjustments to the sizes for clarity, but overall, my project now functions just as intended.

Feel free to explore this codesandbox to see my successful implementation using React and TypeScript. By opening the preview in a new window, you can better understand the functionality. I have also included a custom component that displays the current size of each element as the window is resized, although this step is optional.

The key aspects to focus on are the wrappers containing the resizing elements and the styles within the scss file. Pay close attention to how the 'first-to-shrink' and 'second-to-shrink' classes interact with max-width, min-width, and flex-basis properties set on individual components. Additionally, note that I had to ensure the flex-basis of the container holding two elements equaled the sum of the children's max-widths.

In terms of shrinking and expanding objects, I have categorized them to follow a specific order: Secondary Document, Primary Document, Answer Pane.

The Secondary Document should shrink first with a minimum width of 250px and a maximum width of 500px. Conversely, the Primary Document should shrink last, mirroring the same width constraints. The Answer Pane falls in between, with a minimum width of 150px and a maximum width of 300px.

Once all three objects have reached their minimum sizes, there may be overflow, which is accounted for in my design.

A critical aspect of achieving this layout was utilizing pairs of wrapper/container objects: SecondaryDocument-container housing the Secondary Document, and PrimaryDocument-AnswerPane-container accommodating both the Primary Document and Answer Pane.

https://i.stack.imgur.com/21clV.png

Answer №2

Flexbox doesn't work by simply saying "shrink last"; instead, it operates based on proportional growth and shrink rates among items.

If you find yourself setting too many widths, it may lead to confusion about which properties are actually being applied. Let things flow naturally and observe the outcome.

Here's an illustrative example:

.Item1{
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 350px;
}

.Item2{
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: auto;
}

For more in-depth information on flexbox, check out this comprehensive guide.

Answer №3

I encountered a similar issue recently. If you're not too concerned about individual pixels, one workaround is to utilize flex-grow/flex-shrink properties with significant differences in magnitude.

.Box1 {
    flex-grow: 2
}
.Box2 {
    flex-grow: 2000
}
.Box3 {
    flex-grow: 2000000
}

https://jsfiddle.net/abc123/4/

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

CSS printing displays a blank bar in white color

Attempting to generate a ticket with the dimensions of 203mm x 82mm using HTML and CSS through Python (including cgi, jinja2, weasyprint). The template will be converted into a PDF for users to download via a button on the website. The HTML Body: <body ...

What is the best way to combine a React App and an Express App in order to deploy them as one

After successfully creating an Express and MongoDB API and connecting it to my React Application, I encountered a situation during deployment. It seems that I need to deploy both projects separately, which means I would need two hosting plans for them. H ...

Leverage both props and destructuring in your Typescript + React projects for maximum efficiency!

Is it possible to use both destructuring and props in React? For instance, can I have specific inputs like name and age that are directly accessed through destructuring, while also accessing additional inputs via props? Example The desired outcome would ...

Could I potentially oversee the installation of a package that exclusively includes a single component from Material-UI?

I am looking to streamline my package installation process by only including the specific Material-UI component I need rather than the entire big package. Is there a way to install just the individual component I want to use, such as: import Button from ...

After updating the data, the React Material UI Grid Item fails to render

I am encountering an issue where the code fails to render grid items when there is a change in props.data from the top component. import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Grid from '@ ...

Is the utilization of react-router for developing 'single-page applications' causing a depletion of server resources?

Hello, I am relatively new to the world of web development and would appreciate guidance on any misunderstandings I may have. Currently, I am immersing myself in learning the MERN stack. For my practice project, I am aiming to create a simple two-page webs ...

Is there a way to customize the Material UI Stepper so that a custom icon does not delete the step number, but rather adds the number or random text alongside the

<Stepper linear={false} activeStep={1}> <Step key={1}> <StepButton icon={<LensIcon color={grey300} children={<p>2</p>}/>} onClick={() => console.log('Clicked')} ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

Tips for setting a specific height for an HTML table

For some reason, I can't seem to control the height of this table. I've set it to a maximum of 20px but all the rows are still showing. Here is the CSS: table { border:1px solid black; overflow:hidden; height:20px; max-height:20 ...

Issue with @reach/router where the URL path is updated but the component fails to render after clicking a Link

I recently switched to using @reach/router for a new project after receiving a recommendation on the react-router-dom GitHub page. Despite what should be a simple use case, I am encountering some issues. Initially, I attempted to integrate the @mui BottomN ...

Center a specific item by aligning it with flex

I'm struggling to achieve a simple layout using flexbox, and I can't figure out how to do it. My objective is to have 3 divs aligned in a row, with the middle div (containing "short") centered. A visual representation would make it clearer: The ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

Div refuses to clear floats

Working on an app at and encountering an issue with the main container not clearing floats, causing overflow on the content. Attempted to use this CSS: .clearfix:after { content:""; display: table; clear: both; } Added the class to the main ...

Showing ASP code within a DIV element (inline)

Working on setting up a 'shopping cart' feature on our website, but running into some issues with the ASP code. Does anyone have any advice to offer? In the image below, you can see that when items are added to the cart, the 'total' is ...

Exploring the capabilities of renderOption within Material-UI's AutoComplete functionality

Hey there, I've been pondering a question lately and could really use some help. I've been trying to set up my autocomplete feature to display a label in the options while having a different value. After doing some research, I learned about usin ...

I am attempting to separate this "for" loop in order to generate five distinct DIV elements

Hello there! I am a beginner and I am attempting to create 5 different players by using some code that I found. Here is the code I have been working with: https://codepen.io/katzkode/pen/ZbxYYG My goal is to divide the loop below into 5 separate divs for ...

Adjust the vertical size of the slider in Jssor

Hi there! I'm currently working on a slider that I want to have a dynamic width (100% of the container) and a static height of 550px on PCs, while being responsive on mobile devices. Below is my code snippet: <div class="col-md-6 right-col" id="sl ...

How to use Javascript to toggle a popup containing an autoplaying Vimeo video

I am looking to create a pop-up window containing a Vimeo video inside. I have a div on my webpage with an id of "showVideo". When this div is clicked, I want to display a pop-up (new div with the id of "opened-video"). The "opened-video" div contains an i ...

Error: It seems that in your next.js + expo project, you may have overlooked properly exporting your component from its defined file, or there could be confusion between default and named imports

Whenever I attempt to execute yarn ios, the following error message appears: An issue arose with the element type, as it is invalid. The expected input should be a string for built-in components or a class/function for composite components, yet it receive ...