Search code examples
htmlcsstailwind-css

How to Center the Middle Child Element in a Flexbox Parent with Uneven Widths?


I have a parent container with display: flex and justify-content: space-between. Inside this parent, I have three child elements with uneven widths. Here's a simplified version of my HTML and CSS: I am using tailwind just for clearance

<div class="flex justify-between">
  <div class="w-24">Child 1</div>
  <div class="w-28">Child 2</div>
  <div class="w-20">Child 3</div>
</div>

the second child element is not centered within the parent container because of the uneven widths of the child elements.

I want the second child to be exactly in the center of the parent div, while still maintaining the space-between alignment for the other two children without using 'Absolute' Position

i have tried google but didn't got any expected results


Solution

  • You could consider using a margin offset with the difference in width like:

    <script src="https://cdn.tailwindcss.com/3.4.4"></script>
    
    <div class="flex justify-between">
      <div class="w-24">Child 1</div>
      <div class="w-28">Child 2</div>
      <!-- Using calc() to be more expressive and in case of any configuration changes. -->
      <div class="w-20 ml-[calc(theme(width.24)-theme(width.20))]">Child 3</div>
    </div>
    
    <div class="flex justify-between">
      <div class="w-24">Child 1</div>
      <div class="w-28">Child 2</div>
      <!-- Otherwise, you could use `4` -->
      <div class="w-20 ml-4">Child 3</div>
    </div>

    Or you could consider using a grid layout, with equal-width left and right column grid track sizings:

    <script src="https://cdn.tailwindcss.com/3.4.4"></script>
    
    <div class="grid grid-cols-[1fr_auto_1fr]">
      <div class="w-24">Child 1</div>
      <div class="w-28">Child 2</div>
      <div class="w-20 justify-self-end">Child 3</div>
    </div>