在我使用的许多前端框架中,都有将三元组或 if 分支注入到 html 逻辑中的选项。这是我经常使用的逻辑。一种特殊情况是在没有数据时显示。
我刚刚偶然发现了一种 css 模式,它让我的生活变得更加轻松::only-child 伪类。
在 react 中,我会做这样的“事情”...
{
data.length === 0
? <div>nothing to show.</div>
: <tablewithrecords />
}
在 angular 中,我会做这样的“事情”...
@if (data.length === 0) {
<div>nothing to show.</div>
} @else {
<tablewithrecords />
}
简单来说,我有两种情况。
<h2>no data showing</h2> <ul> <li class="handle-no-data">nothing to show.</li> <!-- <li>data here</li> --> </ul> <h2>data showing</h2> <ul> <li class="handle-no-data">nothing to show.</li> <li>data here</li> </ul>
使用简单的 css 类 .single ...
.handle-no-data:not(:only-child) {
display: none;
}
.handle-no-data:only-child {
display: flex;
}
这个 css 可以简化为 ...
.handle-no-data {
&:not(:only-child) {
display: none;
}
&:only-child {
display: flex;
}
}
这是上面代码的结果...

立即学习“前端免费学习笔记(深入)”;
如您所见,我必须将数据处理移至表级别,但 css 非常直接地处理“无数据”场景。
这太令人兴奋了!
以上就是CSS 独生子而不是条件逻辑的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号