LoginSignup
25
28

More than 5 years have passed since last update.

CSSでやるselectのカスタマイズ2017 ~レスポンシブも~

Posted at

select.png

こういうの、頻出するのでメモがてら。

対応ブラウザ

  • IE10~
  • 泥標準未確認
  • chrome/firefox最新

コード

html
<div class="selectWrap">
    <select name="" id="">
        <option value="">001</option>
        <option value="">002</option>
        <option value="">003</option>
    </select>
</div>
css
select{
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 0;
    margin: 0;
    height: 30px;
    background: transparent;
    position: relative;
    z-index: 1;
    padding: 0 40px 0 10px;
    border: 1px solid #ccc;
}
select::-ms-expand {
    display: none;
}
.selectWrap{
    position: relative;
    display: inline-block;
}
.selectWrap::before{
    content: '';
    position: absolute;
    z-index: 0;
    top: 0;
    right: 0;
    background: #ccc;
    height: 100%;
    width: 30px;
}
.selectWrap::after{
    content: '';
    position: absolute;
    z-index: 0;
    top: 0;
    bottom: 0;
    margin: auto 0;
    right: 9px;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 6px 6px 0 6px;
    border-color: #fff transparent transparent transparent; 
}

ざっとした解説

css
select{
                -webkit-appearance: none;
                -moz-appearance: none;
                appearance: none;
}
select::-ms-expand {
                display: none;
}

で右の三角形を非表示にできる。
以前はfirefox対応に難があったが今の最新版は大丈夫。

非表示にした三角形のかわりに::afterや::beforeでデザインされた三角形を挿入したいところだがselectには::before/::afterが通らない。
代替手段としてselectを包む.selectWrapから::beforeを挿入する。

挿入された要素はselectに重なっているだけなのでクリック判定が無い。
対応としてselectもposition:relativeにしてz-indexを調整し、selectが再前面に来るようにしてやる。
デフォルトだとselectにbackgroundが入っていて三角形が見えなくなってしまうので、background:transparentで背景色を透明にすると矢印が見えるようになる。
borderとかはお好みで。

重ねた三角形の上に文字が重ならないよう、selectのpaddingを調整。

以上でいける。

SP環境でpointer-eventsが通らないため背景を透明色にした上でその裏に配置という力業を使っているが、PCだけならselectWrap::afterとselectWrap::beforeにpointer-events: none;を設定することで手間を減らせる。

25
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
28