css 伪类 :empty —— 隐藏空元素、缺失字段智能提示

应用1:隐藏空元素

有时空元素会影响页面布局,通过:empty可以很方便地将它们隐藏。

<template>
  <ol>
    <li>一</li>
    <li></li>
    <li>三</li>
  </ol>
</template>

<style scoped>
li:empty {
  display: none;
}
</style>
image.png

注意事项:若是v-for循环,很多格式化插件在内容为空时,默认也会生成空格,则无法匹配:empty,解决方案是多加一层div

<template>
  <div class="bigBox">
    <div class="smallBox">1</div>
    <div class="smallBox">2</div>
    <div class="smallBox"></div>
    <div class="smallBox">4</div>
  </div>
</template>
<style scoped>
.smallBox {
  height: 60px;
  width: 100px;
  background: red;
  color: white;
  text-align: center;
  line-height: 60px;
}
.smallBox:empty {
  display: none;
}
.bigBox {
  margin: 30px;
  width: 60%;
  display: flex;
  justify-content: space-around;
}
</style>

应用2:缺失字段智能提示

利用另一个伪类样式::before增加一个content提示

<template>
  <div class="bigBox">
    <div class="smallBox" v-for="(item, index) in list" :key="index">
      <span class="content">{{ item }}</span>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [1, 2, , 4],
    };
  },
};
</script>

<style scoped>
.bigBox {
  width: 60%;
  margin: 20px;
  display: flex;
  justify-content: space-around;
}
.smallBox {
  height: 60px;
  width: 100px;
  background: red;
  color: white;
  text-align: center;
  line-height: 60px;
}
.content:empty::before {
  content: "暂无编号";
}
</style>
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容