在CSS网格布局中扩展单元格

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

我有以下HTML / CSS

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

现在,有时,并且取决于类divmain,有时我没有类divright(换句话说,HTML可能看起来像这样

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
</div>

[我想做的是编写CSS代码,如果div.left不存在,则将div.main扩展到容器div.right的整个宽度。我该怎么办?

css css-grid
1个回答
0
投票

这是更适合flexbox的东西,但是如果您的结构像您指示的那样简单only-child,可以在这里使用。

.main {
  display: grid;
  grid-template-columns: 2fr 1fr;
  margin-bottom: 1em;
}


/* The following is not essential - for decoration purposes only */

.left {
  background-color: green;
  height: 25vh;
}

.left:only-child {
  grid-column: 1 / -1;
}

.right {
  background-color: orange;
}
<div class="main">
  <div class="left">Left</div>
  <div class="right">Right</div>
</div>

<div class="main">
  <div class="left">Left</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.