CSS:如何更改显示网格以使用CSS选择器有条件地伸缩?

Ing*_*nga 5 css css-selectors flexbox css-grid vue.js

我有一个网格,其中填充了Vue中v-for循环中的元素。另外,我有一个搜索栏,可根据输入来减少网格元素。如果元素数大于3,则看起来不错,但是当我只剩下2个元素时,它的间距就太大了。因此,我想更改显示:grid; 显示:flex; 如果网格中的元素小于3。

我尝试过CSS选择器,也许是因为我对编程还很陌生,所以做错了。我知道如何使用JavaScript添加动态类,但是,我想看看使用纯CSS是否可能。

尝试了以下css选择器及其变体:

.grid-container {
    display: grid;
    grid-template-columns: repeat( auto-fit, minmax(290px, 1fr) );
    grid-gap: 3rem;

}

.grid-container:first-child:nth-last-child(n + 2) {
    display: flex;
    display: -webkit-flex;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: flex-start;
    align-items: auto;
    align-content: center;
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*Ian 1

:empty您不能(没有 JavaScript)根据子元素的数量选择父元素(该元素是否有 0 个 ( ) 或更多(子元素)除外):not(:empty)

但是,您可以根据孩子的兄弟姐妹数量来选择所有孩子。这意味着您不能从 更改gridflex,但您可以display: flex一直使用,然后更改元素在 Flexbox 中的流动方式(即通过修改它们的align-selfjustify-selfflex-*属性)。我无法给出具体的示例,因为我看不到您的布局,但我可以在下面给出其工作原理的一般演示。

这是选择器的细分:

    .container > :first-child:nth-last-child(n + 3),
    .container > :first-child:nth-last-child(n + 3) ~ * 
Run Code Online (Sandbox Code Playgroud)
  • .container选择所有具有“容器”类别的内容。
  • >选择容器的直接子项(即,不是子项的子项)。
  • :first-child过滤直接子项,这样您就只有第一个子项。
  • :nth-last-child(n + 3)过滤第一个子元素,以便仅当距离其容器末尾有三个或更多元素时才选择它。如果子级距其容器末尾少于三个元素,则将给出 0 个元素。换句话说,只有当第一个孩子后面有 2 个或更多兄弟姐妹时,它才会保留选择。
  • ~ *选择所选元素后面的所有同级元素。

document.addEventListener("DOMContentLoaded", () => {
  document.querySelector("#clickTarget").addEventListener("click", () => {
    let target = document.querySelector(".container > div:last-child");
    target.parentNode.removeChild(target);
  });
});
Run Code Online (Sandbox Code Playgroud)
/* 0 or more elements */
.container > .child {
  background-color: blue;
}

/* 3 or more elements */
.container > .child:first-child:nth-last-child(n + 3),
.container > .child:first-child:nth-last-child(n + 3) ~ * {
  background-color: green;
}

/* 6 or more elements (must be after the above rule to override it) */
.container > .child:first-child:nth-last-child(n + 6),
.container > .child:first-child:nth-last-child(n + 6) ~ * {
  background-color: orange;
}
Run Code Online (Sandbox Code Playgroud)
<button id="clickTarget">
  Pop Last Element
</button>

<div class="container">
  <div class="child">1</div>
  <div class="child">2</div>
  <div class="child">3</div>
  <div class="child">4</div>
  <div class="child">5</div>
  <div class="child">6</div>
  <div class="child">7</div>
</div>
Run Code Online (Sandbox Code Playgroud)