根据通用容器大小更改网格布局(不使用类)

  • 本文关键字:布局 网格 html css
  • 更新时间 :
  • 英文 :


在下面的示例中,我有两个用于flex项的容器。当容器是300px时,我希望两个150px的框并排(如示例所示(。然而,当容器为150时,我想将容器显示更改为block,使它们相互堆叠(我们不应该看到下面的黄色(。

是否可以在不利用example_1或example_2类并仅引用其容器的情况下编写CSS?我尝试了Chromes@container查询,但没有成功。。。感谢任何帮助!!

.example_1 {
width: 300px;
height: 30px;
background-color: yellow;
}
.example_2 {
width: 150px;
height: 60px;
background-color: yellow;
}
.flex-thing {
display: flex;
flex-direction: row;
width: max-content;
justify-content: stretch;
}
.flex-thing .item {
background-color: red;
width: 150px;
height: 30px;
border: solid 1px black;
}
<div class="example_1">
<div class="flex-thing">
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<br>
<div class="example_2">
<div class="flex-thing">
<div class="item"></div>
<div class="item"></div>
</div>
</div>

如果您希望红框自动换行到第二行,则需要将flex-wrap: wrap;添加到容器中。或者你可以添加

.example_2 .flex-thing{
flex-direction: column;
}

最新更新