CSS网格将高度和宽度拉伸到容器

时间:2019-06-17 02:44:22

标签: html css css-grid

我无法使CSS网格在高度和宽度上都扩展到其父级大小。设置为100%时,宽度会很好地拉伸,但是高度会保持在其初始大小吗?我不确定要在哪里计算高度大小。

当将所有行的grid-template-rows设置为25%时,我认为这将为我提供所需的100%高度,但它不起作用。

JSFiddle

body {
  margin: 10px;
  background-color: red;
  height: 100%;
}

.wrapper {
  display: grid;
  grid-gap: 1px;
  background-color: #fff;
  color: #444;
  grid-template-rows: 25% 25% 25% 25%;
  grid-template-columns: auto auto auto auto;
  grid-template-areas: 
    "a b c d" 
    "e f f g" 
    "h f f i" 
    "j k l m";
  height: 100%;
  width: 100%;
}

.box {
  background-color: #444;
  color: #fff;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-area: a;
}

.b {
  grid-area: b;
}

.c {
  grid-area: c;
}

.d {
  grid-area: d;
}

.e {
  grid-area: e;
}

.f {
  grid-area: f;
}

.g {
  grid-area: g;
}

.h {
  grid-area: h;
}

.i {
  grid-area: i;
}

.j {
  grid-area: j;
}

.k {
  grid-area: k;
}

.l {
  grid-area: l;
}

.m {
  grid-area: m;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
  <div class="box g">G</div>
  <div class="box h">H</div>
  <div class="box i">I</div>
  <div class="box j">J</div>
  <div class="box k">K</div>
  <div class="box l">L</div>
  <div class="box m">M</div>
</div>

2 个答案:

答案 0 :(得分:1)

尝试此操作,将高度从100%更改为100vh

.wrapper {
  display: grid;
  grid-gap: 1px;
  background-color: #fff;
  color: #444;
  grid-template-rows: 25% 25% 25% 25%;
  grid-template-columns: auto auto auto auto;
  grid-template-areas: "a b c d" "e f f g" "h f f i" "j k l m";
  height: 100vh;
  width: 100%;
}

答案 1 :(得分:1)

要跟随屏幕高度,可以使用视口单位vh代替px%

Sizing with CSS3's vw and vh units

body {
  background-color: red;
  height: 100%;
}

.wrapper {
  display: grid;
  grid-gap: 1px;
  background-color: #fff;
  color: #444;
  grid-template-rows: 25% 25% 25% 25%;
  grid-template-columns: auto auto auto auto;
  grid-template-areas: "a b c d" "e f f g" "h f f i" "j k l m";
  height: 100vh;
  width: 100%;
}

.box {
  background-color: #444;
  color: #fff;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-area: a;
}

.b {
  grid-area: b;
}

.c {
  grid-area: c;
}

.d {
  grid-area: d;
}

.e {
  grid-area: e;
}

.f {
  grid-area: f;
}

.g {
  grid-area: g;
}

.h {
  grid-area: h;
}

.i {
  grid-area: i;
}

.j {
  grid-area: j;
}

.k {
  grid-area: k;
}

.l {
  grid-area: l;
}

.m {
  grid-area: m;
}
<div class="wrapper">
  <div class="box a">A</div>
  <div class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
  <div class="box g">G</div>
  <div class="box h">H</div>
  <div class="box i">I</div>
  <div class="box j">J</div>
  <div class="box k">K</div>
  <div class="box l">L</div>
  <div class="box m">M</div>
</div>