猿问

请问如何在CSS网格布局中定位特定的列或行?

如何在CSS网格布局中定位特定的列或行?

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

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

我已经nth-childdiv元素上尝试了选择器,但这不允许我在Grid Layout引擎自动放置项目时指定行或列。

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>


qq_遁去的一_1
浏览 536回答 3
3回答

MM们

CSS无法实现。CSS以HTML元素,属性和属性值为目标。网格列和行没有这些“钩子”。您必须直接定位网格项目。你写了:例如,假设我有一个3行×2列CSS网格布局:grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;。如何从第2列中选择所有元素?grid-container&nbsp;{ &nbsp;&nbsp;display:&nbsp;grid; &nbsp;&nbsp;grid-template-columns:&nbsp;1fr&nbsp;1fr; &nbsp;&nbsp;grid-template-rows:&nbsp;1fr&nbsp;1fr&nbsp;1fr; &nbsp;&nbsp;grid-gap:&nbsp;10px; &nbsp;&nbsp;padding:&nbsp;10px; &nbsp;&nbsp;height:&nbsp;50vh; &nbsp;&nbsp;background-color:&nbsp;gray;}grid-item&nbsp;{ &nbsp;&nbsp;background-color:&nbsp;lightgreen;}grid-item:nth-child(2n)&nbsp;{ &nbsp;&nbsp;border:&nbsp;2px&nbsp;dashed&nbsp;red;}<grid-container> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item></grid-container>

喵喔喔

如果您想要设置行的样式,则应用相同的主体。以上为例:grid-container&nbsp;{ &nbsp;&nbsp;display:&nbsp;grid; &nbsp;&nbsp;grid-template-columns:&nbsp;1fr&nbsp;1fr; &nbsp;&nbsp;grid-template-rows:&nbsp;1fr&nbsp;1fr&nbsp;1fr&nbsp;1fr; &nbsp;&nbsp;grid-gap:&nbsp;10px; &nbsp;&nbsp;padding:&nbsp;10px; &nbsp;&nbsp;height:&nbsp;50vh; &nbsp;&nbsp;background-color:&nbsp;gray;}grid-item&nbsp;{ &nbsp;&nbsp;background-color:&nbsp;lightgreen;}grid-item:nth-child(4n+3),grid-item:nth-child(4n)&nbsp;{ &nbsp;&nbsp;border:&nbsp;2px&nbsp;dashed&nbsp;red;}<grid-container> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item> &nbsp;&nbsp;<grid-item></grid-item></grid-container>
随时随地看视频慕课网APP
我要回答