I'm using flexbox
to display two containers in a parent container that shrinks.
- When the parent container is large enough such that the two
div
s are side by side, I want them to display as far apart as possible. - When the parent
div
shrinks and the seconddiv
wraps to a new line, I want them to display centered horizontally.
Currently I'm using justify-content: space-between
on the parent container which helps them display as far apart as possible but does nothing to center them when the second div
wraps.
This is what the current solution using justify-content: space-between
on the parent div
looks like:
When the parent div is wide, it displays as intended
When the parent div is narrow, it wraps but both are left-aligned instead of centered
Ideally, this is what it would look like:
When the parent div is wide, it maximizes space between them
When the parent div is narrow, it centers both divs horizontally
I've tried all sorts of CSS tricks but a key constraint of this problem is that it must be done with pure CSS, no outside frameworks like React. I found this SO from 6 years ago that's talking about a similar thing and how it can't be done in flexbox
but can be done with grid
assuming the two child div
s are fixed width, in my case however, the children's width
s are not fixed.
Here's an easy-to-read version of my code:
#main {
font-size: 50px;
padding: 10px;
}
#parent {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
#child1 {
background: #FFFFD0;
}
#child2 {
background: #FFD0FF;
}
<div id="main">
<div id="parent">
<div id="child1">
Div #1
</div>
<div id="child2">
Div #2
</div>
</div>
</div>
An important note: I'm only able to specify properties directly on the HTML objects. I don't have a CSS file to create classes, which is why in the code snippet I'm using IDs, since that's essentially the limit of what I'm able to do. I'm building an HTML string to pass from the backend to the frontend to display there. I know this isn't optimal or even good practice but it's what the technical constraints of the problem are.