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


- 失败的 Canvas 360 jquery 插件 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06