Home > Web Front-end > CSS Tutorial > How to Selectively Style Specific CSS Grid Cells Without Using `nth-child`?

How to Selectively Style Specific CSS Grid Cells Without Using `nth-child`?

DDD
Release: 2024-12-18 21:11:17
Original
275 people have browsed it

How to Selectively Style Specific CSS Grid Cells Without Using `nth-child`?

How to Target Specific Grid Cells in CSS

Selecting Rows and Columns Without Grid Children

In a CSS grid layout, nth-child selectors do not suffice to select specific cells as the contents can be dynamically placed within the cells. However, you can use a wrapper element with display: contents to obtain the desired behavior.

Consider the following scenario:

body {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr;
}

.grid-item {
  background: #999;
}
Copy after login

To select all elements within the second column, enclose them within a wrapper with display: contents. This allows you to style the cells in the second column collectively.

body {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  grid-template-columns: 1fr 1fr;
}

.grid-container {
  display: contents;
  grid-column: 2;
}

.grid-item {
  background: #999;
}
Copy after login

This approach ensures that the wrapped elements behave as if they were direct children of the grid container, allowing you to apply styles accordingly.

The above is the detailed content of How to Selectively Style Specific CSS Grid Cells Without Using `nth-child`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template