在CSS网格布局中扩展单元格 [英] Expanding cells in CSS grid layout

查看:75
本文介绍了在CSS网格布局中扩展单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML/CSS

I have the following 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>

现在,有时,根据类maindiv,有时我没有类rightdiv(换句话说,html可能看起来像这样

Now, sometimes, and depending on the div with class main, sometimes I do not have the div with the class right (in other words, the html might look like this

.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.right不存在,可以将div.left扩展到容器div.main的整个宽度.我该怎么办?

What I like to do is write the CSS code in a way that expands div.left to the full width of the container div.main if div.right does not exist. How can I do that?

推荐答案

您可以依赖隐式网格的创建:

You can rely on implicit grid creation:

.main {
  display: grid;
  grid-template-columns: 2fr;
  grid-auto-columns:1fr; /* this will trigger when you add the "right" element */
  grid-auto-flow:column;
  margin:5px;
}


.left {
  background-color: green;
}

.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>

如果您想左移,它也可以工作:

It does also work if you want to remove left:

.main {
  display: grid;
  grid-template-columns: 2fr;
  grid-auto-columns:1fr; /* this will trigger when you add the "left" element */
  grid-auto-flow:column;
  margin:5px;
}


.left {
  background-color: green;
  grid-column-end:1; /* added this */
}

.right {
  background-color: orange;
}

<div class="main">
  <div class="left">Left</div>
  <div class="right">right</div>
</div>

<div class="main">
  <div class="right">right</div>
</div>

这篇关于在CSS网格布局中扩展单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆