0
点赞
收藏
分享

微信扫一扫

一个DOM元素纯CSS实现hover开关

修炼之士 2022-04-29 阅读 78
csshtml

用CSS实现一个开关样式,hover时触发,滑块为正方形,具体大小可随意,如下图

在这里插入图片描述

尽量实现如下要求,可实现一部分:

  1. 开关动作均有动画过度(滑块移位、背景色)
  2. 只用一个dom元素实现
  3. 开关的高度是固定的,但宽度不固定,即宽度为未知父元素的100%,宽度始终大于高度

HTML

	<div class="father">
	  <div class="box">
	  </div>
	</div>

CSS

	.box {
	  height: 50px;
	  width: 100%;
	  background-color: #c2d3e4;
	  transition: background-color 0.25s
	}
	
	.box::before {
	  content: "b";
	  color: white;
	  display: inline-block;
	  background-color: white;
	  position: relative;
	  top: 5px;
	  left: 5%;
	  height: 40px;
	  width: 35%;
	  transition: left 0.25s;
	}
	
	.box:hover {
	  background-color: #348fe4;
	}
	
	.box:hover::before {
	  left: 60%;
	}
	
	/* 父元素宽度任意 */
	.father {
	  width: 100px;
	}
举报

相关推荐

0 条评论