纯css样式改变select选择框的默认样式(改变默认箭头)

时间:2017-10-23
最近在写前端代码时,需要实现一个美观select选择框(默认选择框会有箭头),但是不能使用Js来实现,要使用纯css样式来实现,该如何编写css代码才能使select选择框的样式兼容主流浏览器呢?(如Internet Explorer,火狐苹果浏览器等),具体实现方法请看下文。

实现方法一:使用appearance: none属性

源码如下:

<style>
select {
  margin: 50px;
  border: 1px solid #111;
  background: transparent;
  width: 150px;
  padding: 5px 35px 5px 5px;
  font-size: 16px;
  border: 1px solid #ccc;
  height: 34px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(http://www.stackoverflow.com/favicon.ico) 96% / 15% no-repeat #eee;
}


/* CAUTION: IE hackery ahead */


select::-ms-expand { 
    display: none; /* remove default arrow in IE 10 and 11 */
}

/* target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {
    select {
        background:none\9;
        padding: 5px\9;
    }
}
</style>
<select>
  <option>Apples</option>
  <option selected>Pineapples</option>
  <option>Chocklate</option>
  <option>Pancakes</option>
</select>

在线运行

第二种方法:为select元素设置宽度并使用overflow:hidden以隐藏默认箭头

代码如下:

<style>
.styled select {
  background: transparent;
  width: 150px;
  font-size: 16px;
  border: 1px solid #ccc;
  height: 34px;
}
.styled {
  margin: 50px;
  width: 120px;
  height: 34px;
  border: 1px solid #111;
  border-radius: 3px;
  overflow: hidden;
  background: url(http://www.stackoverflow.com/favicon.ico) 96% / 20% no-repeat #eee;
}
</style>
<div class="styled">
  <select>
    <option>Pineapples</option>
    <option selected>Apples</option>
    <option>Chocklate</option>
    <option>Pancakes</option>
  </select>
</div>

在线运行

方法三:使用css pointer-events属性

代码如下:

<style>
.notIE {
    position: relative;
    display: inline-block;
}

select {
    display: inline-block;
    height:30px;
    width: 150px;
    padding: 2px 10px 2px 2px;
    outline: none;
    color: #74646e;
    border: 1px solid #C8BFC4;
    border-radius: 4px;
    box-shadow: inset 1px 1px 2px #ddd8dc;
    background: #fff; 
}

/* Select arrow styling */
.notIE .fancyArrow {
    width: 23px;
    height: 28px;
    position: absolute;
    display: inline-block;
    top: 1px;
    right: 3px;
    background: url(http://www.stackoverflow.com/favicon.ico) right / 90%  no-repeat #fff;
    pointer-events: none;
    
}
/*target Internet Explorer 9 and Internet Explorer 10:*/
@media screen and (min-width:0\0) { 
    .notIE .fancyArrow
    {
        display:none;
    }
}
</style>
<!--[if !IE]> --> <div class="notIE"> <!-- <![endif]-->
<span class="fancyArrow"></span>
<select>
    <option>Apples</option>
    <option selected>Pineapples</option>
    <option>Chocklate</option>
    <option>Pancakes</option>
</select>
<!--[if !IE]> --></div> <!-- <![endif]-->

在线运行