我有以下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>
现在,有时,并且取决于类div
的main
,有时我没有类div
的right
(换句话说,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
的整个宽度。我该怎么办?
这是更适合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>