如何定位 CSS 网格布局中的特定列或行? [英] How to target a specific column or row in CSS Grid Layout?

查看:27
本文介绍了如何定位 CSS 网格布局中的特定列或行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 CSS 选择特定的网格列或行?

Is it possible to select a specific grid column or row with CSS?

例如,假设我有一个 3 行乘 2 列的 CSS 网格布局:grid-template-rows: 1fr 1fr 1fr;网格模板列:1fr 1fr;.如何从第二列中选择所有元素?例如:grid:nth-child(column:2)(只是我的想法,无效代码).

For example, say I have a 3 row by 2 column CSS Grid Layout: grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;. How would I select all elements from the 2nd column? For example: grid:nth-child(column:2) (just my idea, not valid code).

我在 div 元素上尝试了 nth-child 选择器,但是当网格布局自动放置项目时,这不允许我指定行或列引擎.

I have tried nth-child selectors on the div elements, but this does not allow me to specify row or column when the items are automatically placed by the Grid Layout engine.

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

.item {
  background: #999;
}

<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Right Justify</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>

<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>
<div class="item">
  <p>Customer Name</p>
  <p>Element 1 | Element 2</p>
</div>

推荐答案

CSS 不可能.

CSS 以 HTML 元素、属性和属性值为目标.

CSS targets HTML elements, attributes and attribute values.

网格列和行没有这些钩子".

Grid columns and rows have none of these "hooks".

您必须直接定位网格项目.

You'll have to target the grid items directly.

你写的:

例如,假设我有一个 3 行乘 2 列的 CSS 网格布局:grid-template-rows: 1fr 1fr 1fr;网格模板列:1fr 1fr;.如何从第二列中选择所有元素?

For example, say I have a 3 row by 2 column CSS Grid Layout: grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;. How would I select all elements from the 2nd column?

grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  grid-gap: 10px;
  padding: 10px;
  height: 50vh;
  background-color: gray;
}

grid-item {
  background-color: lightgreen;
}

grid-item:nth-child(2n) {
  border: 2px dashed red;
}

<grid-container>
  <grid-item></grid-item>
  <grid-item></grid-item>
  <grid-item></grid-item>
  <grid-item></grid-item>
  <grid-item></grid-item>
  <grid-item></grid-item>
</grid-container>

这篇关于如何定位 CSS 网格布局中的特定列或行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆