Transforming item design in Flexbox when it wraps

Can styles be applied once an item wraps around?

I have a two-column flexbox layout where the first item is fixed to the left and the second item should be centered in the remaining space. The solution mentioned here involves adding margin: auto to the second item.

// This JavaScript code toggles the container width
document.querySelector('button').addEventListener('click', () => {
  const flexbox = document.querySelector('#flexbox');
  if (flexbox.style.maxWidth) {
    flexbox.style.maxWidth = null;
  } else {
    flexbox.style.maxWidth = '300px';
  }
});
#flexbox {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  border: 2px solid #397298;
}

#flexbox>div {
  background: #8bc6e3;
  padding: 20px;
}

#item2 {
  margin: auto;
}
<div id="flexbox">
  <div id="item1">Flex item 1 with quite a bit of content</div>
  <div id="item2">Flex item 2</div>
</div>

<button style="margin-top: 30px">Toggle shrink container</button>

The question now arises, how can I remove the margin: auto from #item2 when it wraps?
I want it to align to the left side instead of being centered.

Desired Layout:

Not wrapped: https://i.sstatic.net/YKHM7.png Wrapped: https://i.sstatic.net/9o4ll.png

There have been other occasions where I needed to adjust the style of flexbox items when they wrap.
Creating general CSS rules for more complex responsive designs can be challenging. I have experimented with grid layouts, but customizing wrapped items seems to be limited, even though it greatly impacts the page layout and item arrangement.

I am eager for the implementation of container queries as it aims to address this issue, although it is not universally supported by all browsers yet.

Edit: the button is not relevant to the question

The items wrap due to a narrow screen size, not in response to a user action that could be detected by JavaScript.

Answer №1

If you're looking to achieve this using pure CSS, your best option is to utilize media queries. Typically, you'll want to ensure that items wrap when the application is accessed on a phone or other small device. To have more control over the behavior, you can assign a basic width to flex items so you can predict when they will wrap and when they won't.

For example, if you want to display 2 rows of fixed-size content, you can set both items to:

flex: 0 0 50%

This will make each flex item take up 50% of the parent's width. You can then manage the wrapped state with a media query:

@media(max-width 600px) { margin: none; }

It seems that achieving this without JavaScript may be impossible initially. Quoting a user from a Stack Overflow post (link):

In CSS, once the browser renders the page with the initial cascade, it does not reflow the document when an element wraps. Therefore, parent elements are unaware of when their children wrap.

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

Utilizing grease/tampermonkey (or any other browser extension) to filter out specific characters within webpage elements

Forgive me if my language is not accurate, as I am still learning about programming. The forum that I visit has cluttered the page with unnecessary and glitchy images and text for a promotion. This has made the forum difficult to navigate. I was successful ...

Adding images to .xsl using XML

I have created a unique "blog" using XML and XLST. The format of the blog is as follows: <post id="1" category="Miscellaneous"> <ptitle>MiG-21</ptitle> <psubtitle>Mikoyan-Gurevich MiG-21</psubtitle> <image></image& ...

Editing text on an Android device - Removing formatting pieces

I've encountered an issue where trying to remove spans from an EditText using EditText.getText().clearSpans() results in strange behavior. Line feeds start appearing as boxes and any newly set spans are misplaced. My question is: Is there a way to cl ...

Refresh the HTML webpage using AJAX technology

I am trying to implement a simple html page with a single table that updates in the background every 5 seconds. The traditional solution of using <meta http-equiv="refresh" content="5"> is not suitable as it would disrupt the user experience by displ ...

What is the most efficient way to transform HTML into React components effortlessly?

I have been attempting to automate the process of converting HTML into React components. I followed the link below to automatically convert HTML into React components: https://www.npmjs.com/package/html-to-react-components However, I encountered an issue ...

Creating a table in HTML using the innerHTML property

document.getElementById("outputDiv").innerHTML = ""; document.getElementById("outputDiv").innerHTML += "<table border=1 width=100%><tr>"; for(j=1;j<=10;j++) { document.getElementById("outputDiv").innerHTML += "<td align=center>"+St ...

Prevent users from copying and pasting text or right-clicking on the website

I have been struggling to completely disable the ability for users to copy and paste or select text on my website across all devices. After much searching, I came across a solution that I implemented on my site. Below the <body> tag, I inserted the ...

Send information without refreshing the page

Even though there are countless questions similar to this one, I am still struggling to make this work correctly. Any advice on what steps I should take to fix this would be greatly appreciated, as my understanding of jQuery is about 80%. <form action= ...

Flashing background colors on a website

Can anyone explain why this code won't alternate the background color of my website between two different colors? <script type="text/javascript"> function blinkit() { intrvl = 0; for (nTimes = 0; nTimes < 3; nTimes++) { intrv ...

Is it possible to retrieve metadata along with the video content in a single request for an Android application?

While playing videos on Android 4.4+, it appears that multiple network requests are being made. In version 4.4, it seems that one of these requests is for metadata and stops around 2.5 megabytes. However, in 5.0.2, two full requests are fulfilled. Is ther ...

What could be causing the issue with my query that is preventing it from properly displaying information in

Even though I can successfully connect to my database, it keeps pointing out an issue with my query. However, I'm certain that the query is correct as I tested it in my phpMyAdmin console and got the desired results. It's been a while since I wor ...

Instructions on how to export an HTML table to Excel or PDF by including specific buttons using PHP or JavaScript

I created a table to display leave details of employees with sorting options from date to date. Now, I need to include buttons for exporting the data to Excel and PDF formats. Check out the code below: <form name="filter" method="POST"> <in ...

How can I show the last li item in a ul element that extends beyond its parent container?

Chat App Development In my current project, I am developing a chat application using React. The app consists of a list (ul element) that displays messages through individual items (li elements). However, I have encountered an issue where the ul element st ...

Is there something I'm overlooking in my image navigation? It doesn't seem to be interactive

Looking for assistance regarding the issue below. I can't seem to make my image clickable, and I'm not sure what's causing this problem. <img src= "makeup.html.jpg" alt= "Make up by Lauren Evans logo" title= "Make ...

Why is the text getting covered by the drop down menu?

I am currently working with bootstrap classes and I am facing an issue where the drop down menu is overlapping with the text. You can see the problem in the screenshot here: enter image description here <div class="collapse navbar-collapse" ...

Is there a way to modify just the homepage url of the logo on a WordPress website using the OceanWP theme?

My website, abc.com, is set up with Angular for the homepage and WordPress for the blogs. The WordPress site is located in a subfolder within abc.com. You can see the file structure in the image below. I am now looking to change only the homepage link on ...

Inject AngularJS variable bindings into the view alongside HTML code

Is it possible to insert HTML markup into an Angular variable? app.js function myController($scope){ $scope.myItem = '<p>' + Example + '</p>'; } index.html <div ng-controller="myController">{{myItem}}</div&g ...

Adjust the dimensions of the dropdown menus

I've set up 2 dropdown menus, but I'm having trouble adjusting their size. I need them to fill the screen width. Here's my code: <select id="repeatSelect" ng-model="selectedArea"> <option ng-repeat="(key,prop) in result" value=" ...

JQuery submit event not triggering object setting

I'm looking to gather input values from a form and store them in an object for an offer. After trying the following code on submit: $(document).ready(function(){ $('#formOffre').on('submit', function(e) { e.preventDefault ...

Including a JavaScript file using script tags can cause issues with jQuery UI

I've been working on this issue for quite some time now and it's proving to be quite challenging. The problem I'm facing involves incorporating jQuery UI's datepicker into my HTML page which is already being controlled by some Javascri ...