I'm usingflexbox
to display two containers inside a shrunken parent container.
div
are side by side, I want them to appear as far apart as possible.div
shrinks and the seconddiv
wraps, I want them to appear centered horizontally.Currently, I'm usingjustify-content: space- Between
on the parent container, which helps them appear as far apart as possible, but when the seconddiv
wraps , will not center them.
This is what the current solution looks like usingjustify-content: space- Between
on the parentdiv
:
When the parent div is wider, it displays as expected
When the parent div is narrower, it wraps, but both are left aligned instead of centered
Ideally, it should look like this:
When the parent div is wider, it maximizes the space between them
When the parent div is narrower, it will center the two divs horizontally
I've tried various CSS tricks, but a key limitation of this problem is that it must be done using pure CSS, not using an external framework like React. I found this SO 6 years ago and it was talking about something similar and how it can't be done inflexbox
but can be done usinggrid
assuming two childrenThe div
s are fixed width, but in my case the children'swidth
s are not fixed.
Here is an easier 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 #1Div #2
IMPORTANT NOTE: I can only specify properties directly on the HTML object. I don't have a CSS file for creating the classes, which is why in the code snippet I'm using IDs because that's essentially the limit of what I can do. I'm building an HTML string to be passed from the backend to the frontend and displayed there. I know this isn't best practice or even good practice, but that's the technical limitation of the problem.
So, based on the image you posted, I'm assuming you're using the
@media
query in your CSS to make the children wrap on smaller screens. If so, try the following: