Flying memes

How to create a fully customizable pure CSS drop down select

I was working on a new project that uses a highly customised select; as you might know CSS and <select> doesn’t work well together. In fact only a small subset of the CSS properties are accepted by a <select> element and, even worse, this subset vary from one browser to another.

The solution I found rely on radio buttons and labels to mimic the behaviour of an input select. Due this structure the resulting component is fully customisable.

Here’s a working demo on codepen http://codepen.io/sandropaganotti/pen/IeshA

Here’s the code, first the HTML:


<span data-acts-as-select>
  <span>
    <input type="radio" name="value" value="1" id="value1" checked/>
    <label for="value1">First option</label>
    <input type="radio" name="value" value="2" id="value2"/>
    <label for="value2">Second option</label>
    <input type="radio" name="value" value="3" id="value3"/>
    <label for="value3">Third option</label>    
  </span>
</span>

And then the CSS, written with SCSS syntax


span[data-acts-as-select]{
  min-width: 130px;
  height: 23px;
  display: inline-block;
  position: relative;
  
  border: 1px solid gray;
  background-color: lightgray;
  font-family: Georgia;
  
  & > span{
    display: block;
    position: absolute;
    top: 100%;
    left: 0; right: 0;
    
    box-shadow: 0 0 10px rgba(0,0,0,0.5);
  }
  
  &:after{
    position: absolute;
    content: '▾';
    display: block;
    top:0; right:0; bottom:0;
    width: 18px;
    line-height: 23px;
  }
  
  label{
    display: none;
    white-space: nowrap;
    line-height: 23px;
    padding: 0 5px;
    cursor: pointer;
    
    &:hover{
      background-color: lightblue;
    }
  }  
  
  input[type=radio]{
    position: absolute;
    clip: rect(0,0,0,0);
    
    &:checked + label{
      display: block;
      position: absolute;
      bottom: 100%;
      left: 0;
          
      &:hover{
        background-color: transparent;
      }
    }
  }
  
  &:hover label{
    display: block;
  }
    
}

Tags: ,