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.