【问题标题】:If/Else statement in Sass to alter css based on number of items in listSass 中的 If/Else 语句根据列表中的项目数更改 css
【发布时间】:2018-04-08 19:50:03
【问题描述】:

我有一个我正在使用 flex 的项目列表。它们被堆叠在一个水平行中。

我想知道是否可以编写一个基本上执行以下操作的 if/else 语句:

如果列表中有 4 个或更少的项目,请使用 justify-content: space-between,但如果有 5 个或更多项目,请使用 justify-content: space-evenly。

我正在努力弄清楚如何编写这样的东西来测试它,并且在 Sass 文档中找不到任何涵盖这种情况的东西——这样的事情可能吗?

【问题讨论】:

标签: css if-statement sass flexbox


【解决方案1】:

这是在 SASS 中编写 if/else 语句的语法:

$var: true !default; 

@if $var == true {
  // Conditional code
}

$other: single;

@if $other == single {
  // Code for if it’s single
} @else if $other == double {
  // Double code
} @else {
  // Default if it’s neither
}

@if是一个控制指令,类似于@for, @each and @while

【讨论】:

  • 这没有回答问题。 OP 不是在问如何编写 if/else,而是在问如何编写一个特定的 if/else(这是不可能的)。
【解决方案2】:

由于您不能使用 SASS 来计算元素,因此您可以使用 CSS 根据其数量来定位父级的子级(并且当/如果我们获得父级选择器时,我们也可以定位父级:)

基于此解决方案Can CSS detect the number of children an element has?,我们可以将nth-child 更改为针对所有(如果有5 个或更多)。

在您想要更改 justify-content 属性的特定情况下,这将无济于事,因为该属性是在父项上设置的,尽管还有其他方法可以在弹性项目之间创建空间,即自动边距,在哪里可以使用这种方法。

堆栈sn-p

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

li {
    background: blue;
    height: 20px;
    margin: 5px;
}

/* five or more items */
li:first-child:nth-last-child(n+5),
li:first-child:nth-last-child(n+5) ~ li {
    background: red;
}
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

如果这没有帮助,请使用一个小脚本将一个类添加到父级(如果其子级超过 4 个)。

堆栈sn-p

$('ul').each(function(idx, el) {
  if(el.children.length > 4) {
    $(el).addClass('more_than_4');
  }
});
ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

li {
    background: blue;
    height: 20px;
    margin: 5px;
}

ul.more_than_4 {
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-27
    • 2014-03-18
    • 2020-04-05
    • 2017-09-06
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    相关资源
    最近更新 更多