这篇文章给大家分享的是有关css如何实现空载布局的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
空载布局
空载布局指容器内无任何节点时使用其他形式代替的占位布局。还有使用JS判断列表集合为空时显示占位符吗?相信很多使用MVVM框架开发的同学都会使用条件判断的方式渲染虚拟DOM,若列表长度不为0则渲染列表,否则渲染占位符。
<div>
<ul v-if="list.length">...</ul>
<div v-esle>Empty</div>
</div>
然而CSS提供一个空判断的选择器:empty
,这应该很少同学会注意到吧。
:empty
作用于无子节点的节点,该子节点也包括行内匿名盒(单独的文本内容
)。以下三种情况均视为非空状态,若不出现这三种状态则视为空状态,此时:empty
才会触发。

<ul class="empty-layout">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<ul class="empty-layout"></ul>
$empty: "https://yangzw.vip/img/empty.svg";
.empty-layout {
overflow: auto;
width: 200px;
height: 150px;
outline: 1px solid #3c9;
&:empty {
display: flex;
justify-content: center;
align-items: center;
background: url($empty) no-repeat center/100px auto;
&::after {
margin-top: 90px;
font-weight: bold;
content: "没钱就没数据";
}
}
li {
padding: 0 10px;
height: 30px;
background-color: #09f;
line-height: 30px;
color: #fff;
&:nth-child(even) {
background-color: #f90;
}
}
}
另外还存在一种特殊的空载布局
,就是不做任何处理。这样最终渲染的DOM只有容器,若已声明margin/padding/border
但未声明width/height
的情况下,就会出现以下占位效果。无任何子节点的容器还声明着margin/padding/border
,看着都尴尬。

没事,:empty
帮你搞掂!对于无任何子节点的容器直接声明display:none
解决所有无效占位,当然也可作用于指定节点。一招制敌,劲!
// 作用于所有节点
:empty {
display: none;
}
// 作用于指定节点
.empty-layout:empty {
display: none;
}
感谢各位的阅读!关于“css如何实现空载布局”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!