使用纯 CSS 制作步骤进度条
Web

使用纯 CSS 制作步骤进度条

Flying
2015-08-25 / 0 评论 / 137 阅读 / 正在检测是否收录...

步骤进度条的使用场景很多,比如说购物流程 、订单流程、面试流程等都要用到它。网上常见的做法是使用 CSS 图片精灵,该做法的优点是兼容性强,但缺点也很明显:难以自适应设备,而且会加载额外的 图片资源。有没有更好一点的办法呢?下面实例将使用纯 CSS 来制作面试步骤进度条。

steps.svg

需求分析

其实现方法很简单,只需使用 :before 选择器在每一步对应 li 元素添加圆形步骤数字,使用 :after 伪选择器在其后面添加连接线。步骤进度条一般有三种状态:

  • 已经完成的状态
  • 当前正在进行的状态
  • 未完成的状态

本实例中我们简单将已经完成的状态和正在进行的状态设置成同样的样式:数字及连接线变绿,将对于未完成的状态数字及连接线变灰。当前步骤对应 steps li.active,那么已经完成的步骤则对应 steps li.active ~ li。此处用到 CSS3 中的 ~ 选择器来匹配当前 元素之后的所有 li 兄弟元素。

代码实现

  • 如下面 CSS 代码:
.steps {
  position: relative;
  margin-bottom: 100px;
  counter-reset: step;/*创建步骤数字计数器*/
}
/*步骤描述*/
.steps li {
  list-style-type: none;
  font-size: 12px;
  text-align: center;
  width: 25%;
  position: relative;
  color: #777;
  z-index: 2;
  float: left;
}
 /*步骤数字*/
.steps li:before {
  display: block;
  content: counter(step);/*设定计数器内容*/
  counter-increment: step;/*计数器值递增*/
  width: 32px;
  height: 32px;
  background-color: #777;
  line-height: 32px;
  border-radius: 32px;
  font-size: 16px;
  color: #fff;
  text-align: center;
  font-weight: 700;
  margin: 0 auto 8px auto;
}
/*连接线*/
.steps li:after {
  content: '';
  width: 100%;
  height: 4px;
  background-color: #777;
  position: absolute;
  left: 0;
  top: 15px;
  z-index: -1;/*放置在数字层后面*/
}
/*连接线放置在数字层后面*/
.steps li:first-child {
  z-index: 3;
}
.steps li:last-child {
  z-index: 1;
}
/*去掉第一步多出的连接线*/
.steps li:first-child:after {
  width: 50%;
  left: 50%;
}
/*去掉最后一步多出的连接线*/
.steps li:last-child:after {
  width: 50%;
}
/*完成步骤变绿*/
.steps li.active:before {
  background-color: #019875;
}
.steps li.active {
  color: #019875;
}
.steps li.active:before,
.steps li.active:after {
  background-color: #019875;
}
  • 相应的 HTML 代码:

<ul class="steps">
  <li>投递成功
  <li class="active">简历被查看
  <li>待沟通
  <li>面试
</ul>

设置 stepsactive 样式类就行了,是不是很简单?而且是适配移动设备的,很强大吧?

参考实例

访问 codepen 查看示例代码及效果

6

评论 (0)

取消