用纯css改变默认的radio和checkbox的样式

本文介绍如何使用CSS的label伪类::before替代默认的radio和checkbox样式,通过纯CSS实现自定义图片效果,适用于单选框和多选框。但请注意,此方法在IE8以下浏览器不兼容。

本文转载于:猿2048网站https://www.mk2048.com/blog/blog.php?id=0bckbib&title=%E7%94%A8%E7%BA%AFcss%E6%94%B9%E5%8F%98%E9%BB%98%E8%AE%A4%E7%9A%84radio%E5%92%8Ccheckbox%E7%9A%84%E6%A0%B7%E5%BC%8F

利用css的label的伪类(::before)代替checkbox和radio效果:

  1. 优点:需要图片来调整选中前和选中后的样式,纯css搞定

  2. 缺点:兼容性,IE8以下不支持

在线例子:

单选框

男 女

多选框

苹果 橙子

代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>css改变默认的radio和checkbox的样式</title>
  <style>
    input[type="radio"],
    input[type='checkbox'] {
      display: none;
    }

    input[type='radio']+label::before,
    input[type='checkbox']+label::before {
      content: '';
      display: inline-block;
      width: 15px;
      height: 15px;
      margin-right: 6px;
      border-radius: 100%;
      vertical-align: middle;
      border: 1px solid #E4E4E4;
      background: #FFFFFF;
      background-image: url('https://i.loli.net/2018/07/20/5b517d0bf066a.png');
      background-position: 0px 0px;
    }

    input[type='radio']:hover+label::before,
    input[type='checkbox']:hover+label::before {
      background-position: -15px 0px;
    }

    input[type='radio']:checked+label::before,
    input[type='checkbox']:checked+label::before {
      background-position: -15px -15px;
    }
  </style>
</head>

<body>
  <p>单选框</p>
  <input type="radio" name="sex" value="man" id="man" checked>
  <label for="man">男</label>
  <input type="radio" name="sex" value="female" id="female">
  <label for="female">女</label>
  <p>多选框</p>
  <input type="checkbox" name="fruits" value="apple" id="apple" checked>
  <label for="apple">苹果</label>
  <input type="checkbox" name="fruits" value="orange" id="orange">
  <label for="orange">橙子</label>
</body>

</html>

本文转载于:猿2048➧https://www.mk2048.com/blog/blog.php?id=0bckbib&title=%E7%94%A8%E7%BA%AFcss%E6%94%B9%E5%8F%98%E9%BB%98%E8%AE%A4%E7%9A%84radio%E5%92%8Ccheckbox%E7%9A%84%E6%A0%B7%E5%BC%8F

转载于:https://my.oschina.net/u/4181724/blog/3093743

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值