I have 4 div’s and i want two of these left of the container and other two on the right.
i manage to do it with like this do you think is that a good aproach in tailwind-css or in general?
div.flex {
background-color: #eee;
outline: 1px solid #999;
}
div.flex > * {
background-color: #ccc;
outline: 1px solid #333;
}
<script src="https://cdn.tailwindcss.com/3.3.2"></script>
<div class="sticky w-full h-16 gap-2 flex items-center">
<div class="ml-4 w-8 h-8"></div>
<div class="w-8 h-8"></div>
<div class="grow"></div>
<div class="w-8 h-8"></div>
<div class="mr-4 w-8 h-8"></div>
</div>
4
Answers
Yes, using a spacer element is an efficient approach in flexbox. Your code seems to be correctly placing two divs on the left and two divs on the right, with a spacer in between. It’s a good practice to use flexbox and leverage the
gap
utility in Tailwind CSS for spacing.Tailwind CSS utility classes
The
flex-grow
class is used to make the third<div>
element occupy all the available space within the flex container, pushing the remaining elements to the right. Theml-auto
class can also be used instead offlex-grow
to achieve the same effect.No, HTML elements should not be introduced to add styles. Your HTML code should only reflect your content and CSS should be used to style/position your elements.
Use
ml-auto
on the third element(Disclaimer: I am not a Tailwind user, so I don’t know if using spacer elements is idiomatic in Tailwind or not – but if this were my own project I’d avoid them: simpler HTML with fewer moving-parts is more maintainable, imo)
You don’t need any placeholder elements in your HTML – you can use CSS’s flexbox’s built-in support for customizing element location and spacing using
margin: auto
, like so:An alternative approach is to use two child flex containers, with the grandparent flex container having
justify-content: space-between;
:Also, instead of using explicit margins via
.ml-4
and.mr-4
(which setmargin-left/right: 1rem;
respectively) consider just usinggap: 1rem;
: