Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Horizontally center last items in grid-system by using TailwindCSS utilities #18411

rozsazoltan started this conversation in Show and tell
Discussion options

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>
You must be logged in to vote

Replies: 1 comment

Comment options

Does anyone have better ideas for naming? My brain feels pretty mushy right now.

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant

AltStyle によって変換されたページ (->オリジナル) /