我有一个带有 display: flex 和 justify-content: space- Between 的父容器。在这个父元素中,我有三个宽度不均匀的子元素。这是我的 HTML 和 CSS 的简化版本: 我使用顺风只是为了清关
<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>
由于子元素的宽度不均匀,第二个子元素未在父容器中居中。
我希望第二个子元素正好位于父 div 的中心,同时仍然保持其他两个子元素之间的空间对齐,而不使用“绝对”位置
我尝试过谷歌,但没有得到任何预期的结果
您可以考虑使用宽度差异的边距偏移,例如:
<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>
或者您可以考虑使用网格布局,具有等宽的左右列网格轨道尺寸:
<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>