How to target a specific column or row in CSS Grid Layout?(如何定位 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 网格布局中的特定列或行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何定位 CSS 网格布局中的特定列或行?


基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01