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 网格布局中的特定列或行?


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01