伪元素的妙用

1. 使用自增功能实现列表序号

<ul class="sort-list">
  <li class="sort">元素列表</li>
  <li class="sort">元素列表</li>
  <li class="sort">元素列表</li>
  <li class="sort">元素列表</li>
  <li class="sort">元素列表</li>
</ul>
复制代码
.sort-list {
  counter-reset: li;
  list-style-type: none;
}
.sort {
  color: #000;
  background: #ccc;
  margin-top: 14px;
  padding: 15px;
  opacity: .8;
  width: 300px;
}
.sort::before {
  content: counter(li)". ";
  counter-increment: li;
}
复制代码

2. 使用after实现自动换行

<div class="poem">
  <span class="break-line">故人西辞黄鹤楼</span>
  <span class="break-line">烟花三月下扬州</span>
</div>
复制代码
.break-line::after {
  content: "\A";
  white-space: pre;
}
复制代码

3. 使用css的attr函数实现placeholder

<div class="input-text attr-placeholder" contenteditable="true" data-placeholder="请输入文字"></div>
复制代码
.input-text {
  width: 300px;
  padding: 10px;
  font-size: 20px;
  line-height: 1.4;
  border: 1px solid #ccc;
  outline: none;
}

.attr-placeholder:empty::before {
  content: attr(data-placeholder);
  color: #b2b2b2;
}
复制代码

4. 使用伪元素实现背景图片

<div class="fake-el-img"></div>
复制代码
.fake-el-img::before {
  content: url('https://user-gold-cdn.xitu.io/2019/9/3/16cf654fcfd61673?w=533&h=300&f=jpeg&s=16052');
}
复制代码

妖尾图片

5. 使用伪元素扩大可点击区域

<span class="btn">button</span>
复制代码
.btn {
  font-size: 18px;
  font-family: Helvetica, Tahoma, Arial;
  line-height: 1em;   /*使用em做为单位,即便字体变化,按钮的总体样式也会按比例跟随变化*/
  color: #fff;
  background: linear-gradient(135deg,#fce,#cce);
  padding: .5em 1.5em;
  border-radius: 2em;
  display: inline-block;
  position: relative;
}

.btn::before {
  content: '';
  position: absolute;
  left: -5px;
  right: -5px;
  top: -5px;
  bottom: -5px;
}
复制代码

能够根据本身想要添加的范围,修改值,目前为5pxcss

博客地址 gitbook小册html

相关文章
相关标签/搜索