I'm using flexbox
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 second div
wraps, I want them to appear centered horizontally. Currently, I'm using justify-content: space- Between
on the parent container, which helps them appear as far apart as possible, but when the second div
wraps , will not center them.
This is what the current solution looks like using justify-content: space- Between
on the parent div
:
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 in flexbox
but can be done using grid
assuming two children The div
s are fixed width, but in my case the children's width
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 id="main"> <div id="parent"> <div id="child1"> Div #1 </div> <div id="child2"> Div #2 </div> </div> </div>
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.
P粉3409802432024-02-22 16:46:45
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:
.main { width: 100%; } .parent { display: flex; justify-content: space-between; } .child { width: fit-content; padding: 2rem; } .child:nth-child(odd) { background: lightblue; } .child:nth-child(even) { background: pink; } @media only screen and (max-width: 992px) { .parent { width: fit-content; flex-direction: column; margin: 0 auto; } .child { margin: 0 auto; } }
DIV 1Hell yeah! I'm the meanest...