How can I apply justify-content: space-between
based on the center of divs? For example let’s assume I have three divs of different sizes. I want to make them justify in a way that the second div’s center is at the center of its container
.flex {
display: flex;
width: 1000px;
height: 200px;
background-color: black;
justify-content: space-between;
position: relative;
}
.first {
width: 150px;
background-color: red;
}
.second {
width: 200px;
background-color: green;
}
.third {
width: 100px;
background-color: blue;
}
.center {
width: 10px;
height: 10px;
background-color: white;
position: absolute;
top: calc(50% - 5px);
left: calc(50% - 5px);
}
<div class="flex">
<div class="center"></div>
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>
</div>
As you can see, it is not centered. Or in case of four divs, I want the center of container div to be in the middle of second and third divs. Is there a built in way to achieve this behavior? Thanks in advance
3
Answers
Make use of
You don’t need
<div class="center"></div>
I can’t think of any way to do this using only a flexbox with the different-sized elements as direct children, if you need support for an arbitrary number of elements. My recommendation would be to use a flexbox with an extra layer of child elements. Or you could use a table, but I think the flexbox is cleaner.
I could come this kind of approch. We can get number of child element and find the middle element and create your center DIV inside there
or
if dont have an one middle element we can add the center DIV between two middle element
Add any number of DIV element and see