The quantity query is a technique that utilizes the combination of nth-last-child and the subsequent-sibling combinator (the tilde symbol ~
) to apply styles to a group of elements when the number of elements in the group exceeds a certain threshold.
Quantity Query and :has
Selector
The quantity query can be incredibly powerful when used in conjunction with the :has
selector! The article Conditional CSS with :has and :nth-last-child written by Ahmad demonstrates 7 use cases of the quantity query combined with the :has
selector. I chose one to showcase its power!
When creating a modal or dialog, it’s common to include one or multiple buttons at the bottom. By default, we can position the button in the center. Additionally, we can use a quantity query and the :has selector to place the buttons at the end of the block when there are two or more buttons.
When there are two or more buttons, the <div class="actions">
will position the buttons to the rightmost by changing the justify-content
to flex-end
.
When there is only one button, the :has
selector and quantity query will not trigger, so the button will be placed in the center by default.
References