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

Incorporating Typescript with Chart.js: The 'interaction.mode' types do not match between these two entities

I am working on developing a React Functional Component using Typescript that showcases a chart created with chartjs. The data and options are passed from the parent component to the child component responsible for rendering the line chart. During the pr ...

CSS animations for loading page content

Currently, I am incorporating animations into my project using HTML5 and CSS3, and the progress has been smooth. I have been able to achieve effects such as: #someDivId { position: absolute; background:rgba(255,0,0,0.75); transition: all 0.7s ...

Trouble with React Material-UI Select component onChange event

I encountered an issue while using Material-UI select where I am unable to access the selected value due to a warning message: index.js:1 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside S ...

Rotate Chevron icon downwards on mobile devices in a Multilevel Dropdown Bootstrap 4

Bootstrap 4 is being utilized for my current project, I am looking to modify the rotation of the chevron icon in a multi-level dropdown menu specifically on mobile devices when the parent link is tapped, Here is the code snippet for the multi-level dropd ...

Certain issues arise when adjusting the padding within the background color of solely the inline text element

Appreciate your time. I'm working on adding background color to the TEXT exclusively, and have successfully done so by styling .post-title { text-transform:capitalize; margin-top:4px; margin-bottom:1px; font-size:22px; background-color:#FFF; dis ...

Exploring ways to check async calls within a React functional component

I have a functional component that utilizes the SpecialistsListService to call an API via Axios. I am struggling to test the async function getSpecialistsList and useEffect functions within this component. When using a class component, I would simply cal ...

Using TypeScript with React and Redux to create actions that return promises

Within my React application, I prefer to abstract the Redux implementation from the View logic by encapsulating it in its own package, which I refer to as the SDK package. From this SDK package, I export a set of React Hooks so that any client can easily u ...

Uppercase the initial letter in a term to indicate a standard condition

I'm struggling to override the CSS in material UI. Even though I tried capitalizing both words, it only changes on selected and hover states, Is there a way to change it in the normal state as well? I've tried debugging but can't seem to fin ...

How to choose an option from a ReactJS dropdown using Selenium in Java

I am currently working with a ReactJS front end application that features a dropdown box. When this dropdown box is clicked, it displays elements inside of it and requires the user to select checkbox(es). However, when attempting to inspect the values with ...

Ensuring that the second level unordered list is set to a height of 100% of the first unordered list, rather than the

I'm working with this menu http://codepen.io/alexandernst/pen/oxpGYQ (I wanted to include it here but the result viewer on SO is causing some display issues...) and I am trying to ensure that the second and third level ul elements are the same height ...

Setting the initial state value using the useEffect Hook

I want to initialize a value k using the useState hook only once and trigger the useEffect hook after the component mounts. The useEffect callback will create an intersection observer to update the state of k when needed, causing the component to re-render ...

How to resolve undefined callback when passing it to a custom hook in React Native

I'm facing an issue with passing a callback to my custom hook: export default function useScreenshotDetection(onScreenshot) { useEffect(() => { ... onScreenshot(); ... }, []); } Strangely, the callback is not being detected ...

Changing a p element to a div and adding a class in Bootstrap 4.5

To maintain consistency, I prefer using <div class='something'>BIO</div> over <p>BIO</p>. In Bootstrap 4.5, is there a similar class that achieves the same result? I'm not very skilled in CSS, so please forgive me i ...

Can CSS rules be inserted outside of the Header section?

Question: Can CSS styles be declared outside the “HEAD” element of an “HTML” page ? While working within a CMS where access to the header tag is restricted, is there a method to include CSS rules within the <BODY> of the ...

What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page: <Link href={`/products/${id}`} key={id}> <a> {/* other components */} </a> </Link> I believe the problem l ...

Designing a dynamic wizard layout using Bootstrap 4 tabs, however encountering issues with the button functionality limited to a

My goal is to create a seamless navigation experience between tabs. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/b ...

The voting system will increase or decrease by 1 to 5 during each round

Recently, I added a voting system to my website inspired by this source. It's functioning well, but there is an issue where each vote can sometimes count for more than one. You can view the source code on the original website and test it out live here ...

Steer clear of using React Ajax in combination with FileUpload and FormData if you want to prevent the

Upon completing an AjaxCall using formData and files_upload, the entire page inexplicably reloads. This issue does not occur with a standard Ajax Call. It's important to note that there is no FORM tag present in the codebase as we are utilizing REACT ...

A guide on triggering actions when the location changes using react router v4

While using react-router-4.0.0-beta.4 in conjunction with redux, I am exploring the most effective approach to dispatch actions when a route changes. In previous versions, there was an API/event hook for this purpose (link: https://github.com/ReactTraini ...

Issue with aligning label to the left in Material UI select component causing unexpected behavior

Is there a way to left align a label for a select component created with Material UI without it going outside the formControl? I'm looking for a solution that keeps the label within the formControl but does not require using labelPlacement or FormCont ...