如何为不同的媒体查询添加网格项标题?

问题描述 投票:0回答:1

我刚刚学会了如何使用 css grid。我想将其应用到某个案例上:

在大屏幕宽度上,我想要以下网格结构:

#  title1 title2 title3
1  val11  val12  val13
2  val21  val22  val23

在窄屏幕宽度上,我想要以下网格结构:

# 1 
title1 val11
title2 val12
title3 val13

# 2 
title1 val21
title2 val22
title3 val23

我想我可以使用“完整”网格,并在不同的媒体查询上仅显示其中的一部分: 例如

#     title1(**)       title2(**)       title3(**)              
# 1   title1(*) val11  title2(*) val12  title3(*) val13
# 2   title1(*) val21  title2(*) val22  title3(*) val23


(*) hidden on large screen width
(**) hidden on narrow screen width

但是有没有更简单的方法,无需重复标题单元格?

css css-grid
1个回答
0
投票

您可以使用伪元素来管理它。

我已经完成了一个片段,将一个类添加到网格中以进行窄或宽显示。

您可以对其进行调整以轻松使用媒体查询

.parent {
  display: grid;
  gap: 4px;
  border: solid 1px black;
  margin: 10px;
  grid-template-columns: repeat(3, 150px);
  width: fit-content;
}

.parent.narrow {
  grid-template-columns: repeat(2, 150px);
}

.child {
  height: 25px;
  display: grid;
}

.narrow .child {
  display: grid;
  grid-template-columns: 150px 150px;
  grid-column: 1 / 3;
}

.parent.wide .child:nth-child(-n+3) {
  grid-row: 1 / 3;
  display: grid;
  grid-template-rows: 30px 30px;
}

.child:before {
  background-color: white;
}

.narrow div:nth-child(3n+1):before,
.parent div:nth-child(1):before {
  content: "title1";
}

.narrow div:nth-child(3n+2):before,
.parent div:nth-child(2):before {
  content: "title2";
}

.narrow div:nth-child(3n):before,
.parent div:nth-child(3):before {
  content: "title3";
}

.c1 {
  background-color: lightgreen;
}

.c2 {
  background-color: lightblue;
}

.c3 {
  background-color: mistyrose;
}
<div class="parent narrow">
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
</div>
<div class="parent wide">
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
  <div class="child c1">Child 1</div>
  <div class="child c2">Child 2</div>
  <div class="child c3">Child 3</div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.