-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Horizontally center last items in grid-system by using TailwindCSS utilities #18411
rozsazoltan
started this conversation in
Show and tell
-
Trying to place the last item horizontally center. But its always rendering at left.
<div class="grid grid-cols-4 gap-4 text-center"> ... <div class="border border-gray-800"> <h5 class="text-2xl mb-2">Heading</h5> <p>Content Content Content Content</p> </div> </div>
This is not achievable with CSS alone. It's a characteristic of the grid display. You can solve it using flex, and by adjusting the width of the child elements, you can ensure you always have 4 columns.
<div class="flex flex-wrap gap-4 justify-center text-center [&>*]:w-[calc((100%-var(--spacing)*12)/4)]"> ... <div class="border border-gray-800"> <h5 class="text-2xl mb-2">Heading</h5> <p>Content Content Content Content</p> </div> </div>
This could be improved using CSS variables, since the number of gaps depends on the number of items in a row, and is always one less than that.
@utility special-grid { display: flex; flex-wrap: wrap; --col-num: var(--special-grid-col-num, 1); --gap-num: calc(var(--col-num) - 1); & > * { width: calc((100% - var(--gap-width, 0) * var(--gap-num, 0)) / var(--col-num, 1)); } } @utility special-grid-col-* { --special-grid-col-num: --value(integer, [integer]) } @utility gap-* { --gap-width: calc(var(--spacing) * --value(integer)); --gap-width: --value([*]); }
<div class="special-grid special-grid-col-4 xl:special-grid-col-6 justify-center gap-4 text-center"> ... <div class="border border-gray-800"> <h5 class="text-2xl mb-2">Heading</h5> <p>Content Content Content Content</p> </div> </div>
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment
-
Does anyone have better ideas for naming? My brain feels pretty mushy right now.
Beta Was this translation helpful? Give feedback.
All reactions
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment