Is it possible to apply styles once an item wraps?
I have a 2 column flexbox where the first item sticks to the left and the one on the right should be in the center of the remaining space. The solution is to add margin: auto
to the second item.
// Not relevant for the question - toggle 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 some content</div>
<div id="item2">Flex item 2</div>
</div>
<button style="margin-top: 30px">Toggle shrink container</button>
Now the question is, how can I remove the margin: auto
of #item2
if it's wrapped?
I want it to be on the left side and not centred.
This is what I want:
There were multiple other instances where I wanted to change the style of the flexbox items when they wrap.
I find it very hard sometimes to write general CSS rules on more complex responsive designs. Did a lot of fiddling with grid as well, but it seems that there is no option to customize the wrapped items, even though it changes the page layout and item arrangement quite a lot.
I'm looking forward to container queries that go in this direction, but it's not yet supported by all browsers.
Edit: the button is not question relevant
The items wrap because of a narrow screen size, not because a user makes an action that could be caught by JS.