css 超实用的:empty —— 隐藏空元素、缺失字段智能提示

简介: css 超实用的:empty —— 隐藏空元素、缺失字段智能提示

应用1:隐藏空元素

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

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

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

注意事项:若是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:缺失字段智能提示

<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>

<template>
  <table border>
    <tr>
      <td>1</td>
      <td></td>
      <td>3</td>
    </tr>
  </table>
</template>


<style scoped>
td {
  min-width: 100px;
  text-align: center;
}
td:empty::before {
  content: "暂无数据";
}
</style>

类似的常用场景有:

.searchResult:empty::before {
   content: '没找到相关内容';
   display: block;
   line-height: 300px;
   text-align: center;
   color: gray;
}
.articleList:empty::before {
   content: '还没有发表任何文章';
   display: block;
   line-height: 300px;
   text-align: center;
   color: gray;
}

全局空元素样式的css

.empty:empty::before {
   content: '暂无数据';
   display: block;
   line-height: 300px;
   text-align: center;
   color: gray;
}
目录
相关文章
|
11天前
|
前端开发
css元素实现垂直竖直万能居中
css元素实现垂直竖直万能居中
11 0
|
13天前
|
移动开发 前端开发 JavaScript
CSS3 标签元素显示模式
CSS3 标签元素显示模式
|
6天前
|
前端开发
css的flex布局中使用margin:auto智能分配剩余空间
css的flex布局中使用margin:auto智能分配剩余空间
12 1
|
6天前
|
前端开发
前端 CSS 经典:元素倒影
前端 CSS 经典:元素倒影
9 1
|
6天前
|
前端开发
你不知道的css——2. 百分比高度失效,绝对定位和非绝对定位元素的宽高百分比计算方法的不同
你不知道的css——2. 百分比高度失效,绝对定位和非绝对定位元素的宽高百分比计算方法的不同
7 1
|
7天前
|
前端开发
css实用技巧——绝对定位元素的水平垂直居中
css实用技巧——绝对定位元素的水平垂直居中
14 2
|
9天前
|
前端开发 JavaScript
使用JavaScript动态更改元素的CSS属性
【6月更文挑战第29天】使用JavaScript动态更改元素的CSS属性
17 3
|
10天前
|
前端开发 开发者
CSS属性选择器:精确定位元素的利器
CSS属性选择器:精确定位元素的利器
16 4
|
11天前
|
前端开发
|
17天前
|
移动开发 前端开发 HTML5
有关CSS中排版常见问题(清除默认样式问题 + 元素居中问题 + 元素之间的空白问题 + 行内块的幽灵空白问题)
有关CSS中排版常见问题(清除默认样式问题 + 元素居中问题 + 元素之间的空白问题 + 行内块的幽灵空白问题)