[英]If/Else statement in Sass to alter css based on number of items in list
我有一个要用flex样式的项目列表。 它们堆叠在一排。
我想知道是否可以编写基本执行以下操作的if / else语句:
如果列表中有4个或更少的项目,则在两端之间使用justify-content:空格,但是,如果列表中有5个或更多的项目,请使用justify-content:均匀空间。
我正在努力地思考如何编写这样的东西来对其进行测试,却无法在Sass文档中找到涵盖这种情况的任何东西-这样可能吗?
由于您不能使用SASS来计数元素,因此可以使用CSS根据父对象的数量来定位它们(以及/当我们获得父选择器时,我们也可以将父对象作为目标:)
基于此解决方案, CSS可以检测元素具有的子级数目吗? 如果有5个或更多,我们可以将nth-child
更改为全部目标。
在您的特定情况下,您想更改justify-content
属性,但这无济于事,因为该属性是在父级上设置的,尽管还有其他方法可以在弹性项目之间创建空间,例如自动边距,该方法可以使用。
堆栈片段
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)。
堆栈片段
$('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>
这是在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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.