css下拉框样式美化
中所周知,表单中的select下拉框元素是没办法直接通过css样式调整的,所以网上出现了很多针对这个问题的解决方法,今天我就找到了一个用html+css做的select下拉框,它是通过多个radio单选框来模拟实现select下拉框的选择效果。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus">
<meta name="Author" content="wcdstudio">
<title>css下拉框样式美化</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div tabindex="1">
<input type="radio" name="radiobutton2" value="radiobutton" id="opt1" checked /><label for="opt1">在样式中调整opacity为0(透明)</label>
<input type="radio" name="radiobutton2" value="radiobutton" id="opt2" /><label for="opt2">即可隐藏默认radio样式</label>
<input type="radio" name="radiobutton2" value="radiobutton" id="opt3" /><label for="opt3">上海</label>
</div>
<style>
.selectx{display:flex;width:300px;flex-wrap:wrap;position:relative;height:40px;}
.selectx label{width:300px;line-height:40px;display:block;display:flex;position:absolute;top:0;pointer-events:none;order:2;z-index:1;}
.selectx label:hover{background:#ddd;}
.selectx:focus label {position:relative;pointer-events:all;}
.selectx input:checked+label{order:1;z-index:2;background:#ddd;}
</style>
</form>
</body>
</html>
直接复制上面的代码,可以更容易看到当我们选择相应的选项的时候,对应的radio选项也是被选中状态,接着下来就是通过css样式来美化的问题了。可以下载 css表单 浏览。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus">
<meta name="Author" content="wcdstudio">
<title>css下拉框样式美化</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div tabindex="1">
<input type="radio" name="radiobutton2" value="radiobutton" id="opt1" checked /><label for="opt1">在样式中调整opacity为0(透明)</label>
<input type="radio" name="radiobutton2" value="radiobutton" id="opt2" /><label for="opt2">即可隐藏默认radio样式</label>
<input type="radio" name="radiobutton2" value="radiobutton" id="opt3" /><label for="opt3">上海</label>
</div>
<style>
*{margin:0;padding:0;}
.selectx{display:flex;width:300px;flex-wrap:wrap;position:relative;height:40px;margin:100px;}
.selectx input{position:absolute;top:50%;transform:translateY(-50%);right:-30px;opacity:0;}
.selectx label{width:300px;line-height:40px;display:block;display:flex;position:absolute;top:0;pointer-events:none;order:2;z-index:1;padding:0 10px;box-sizing:border-box;border:1px solid #ddd;border-top:none;}
.selectx label:hover{background:#eee;}
.selectx:focus{outline:none;}
.selectx:focus label {position:relative;pointer-events:all;}
.selectx input:checked+label{order:1;z-index:2;border:1px solid #ddd;background:#fff;position:relative;}
.selectx input:checked+label:after{content:'';display:block;position:absolute;top:50%;transform:translateY(-50%);right:10px;border-top:5px solid #ddd;border-left:5px solid transparent;border-right:5px solid transparent;}
</style>
</form>
</body>
</html>