Skip to content Skip to sidebar Skip to footer

Are There Selectors That Target Elements In Certain Grid Positions?

I have a CSS grid with a bunch of auto-flowed grid items. Sometimes the grid items are one 1 x 1 track, and sometimes they're 2 x 2 tracks, so I do not know from the source order w

Solution 1:

There are no selectors for matching elements in certain grid positions when the grid is rendered using CSS. The grid-structural selectors introduced in Selectors 4 only match elements based on grid structures expressed in document semantics, such as tables in HTML (which also means that they cannot match elements based on grid semantics when they are non-tabular elements rendered using display: table-* either).

A similar problem exists with flexbox: there are no selectors for matching specific flex items based on how they are laid out. In general, there are no selectors matching elements based on their layout as governed by CSS. Selectors only match elements based on document semantics (source order, etc).

To style the desired elements, you will need to identify them using some other means, such as a client-side script, or some backend logic that labels elements with classes based on their grid positions (if the grid layout is configured within the backend). How you do this is outside the scope of this question.

Solution 2:

I recently published an NPM package, self-aware-grid, for helping with this kind of thing. It determines which elements are on which column and row, and applies CSS classes accordingly so you can style those elements however you see fit.

I haven't tested it on grids with children of varying sizes, so I would expect that, unless by some serendipitous accident, only same-size children are supported.

If you want to try it out:

Post a Comment for "Are There Selectors That Target Elements In Certain Grid Positions?"