¿Cómo diseñar un menú desplegable con solo CSS?


¿Hay una forma de aplicar estilo a un menú desplegable de <select> solo con CSS?

Necesito estilizar un formulario <select> tanto como sea humanamente posible, sin ningún JavaScript. ¿Cuáles son las propiedades que puedo usar para hacerlo en CSS?

Este código debe ser compatible con todos los navegadores principales:

  • Internet Explorer 6,7 y 8
  • Firefox
  • Safari

Sé que puedo hacerlo con JavaScript: Ejemplo.

Y no estoy hablando de estilo simple. Quiero saber, lo mejor que podemos hacer con CSS solamente.

Encontré preguntas similares en Stack Overflow.

Y este en Doctype.com.

Author: Skip Jack, 2009-12-13

24 answers

Aquí hay 3 soluciones:

Solución #1-apariencia: ninguno - con solución alternativa ie10-11 ( Demo )

Para ocultar la flecha predeterminada appearance: none en el elemento select, agregue su propia flecha personalizada con background-image

select {
   -webkit-appearance: none; 
   -moz-appearance: none;
   appearance: none;       /* remove default arrow */
   background-image: url(...);   /* add custom arrow */
}

Soporte del navegador:

appearance: none tiene muy buen soporte para navegadores ( caniuse ) - a excepción de ie11-y firefox 34 -

Podemos mejorar esta técnica y agregar soporte para ie10 e ie11 por añadiendo

select::-ms-expand { 
    display: none; /* hide the default arrow in ie10 and ie11 */
}

Si ie9 es una preocupación-no tenemos forma de eliminar la flecha predeterminada (lo que significaría que ahora tendríamos dos flechas), pero, podríamos usar un selector ie9 funky al menos deshacer nuestra flecha personalizada-dejando intacta la flecha de selección predeterminada.

/* target Internet Explorer 9 to undo the custom arrow */
@media screen and (min-width:0\0) {
    select {
        background-image:none\9;
        padding: 5px\9;
    } 
}

Todos juntos:

select {
  margin: 50px;
  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;
    }
}
<select>
  <option>Apples</option>
  <option selected>Pineapples</option>
  <option>Chocklate</option>
  <option>Pancakes</option>
</select>

Esta solución es fácil y tiene un buen soporte para navegadores, generalmente debería ser suficiente.


Si el soporte del navegador para ie9-y firefox 34-es necesario entonces seguir leyendo...

Solución #2 Trunca el elemento select para ocultar la flecha predeterminada (Demo)

(Leer más aquí)

Envuelva el elemento selecten un div con un ancho fijo y overflow:hidden.

Luego dale al elemento select un ancho de aproximadamente 20 píxeles mayor que el div.

El resultado es que la flecha desplegable predeterminada del elemento select estará oculta (debido al overflow:hidden en el contenedor), y puede colocar cualquier imagen de fondo que desee en el lado derecho del div.

La ventaja de este enfoque es que es cross-browser (Internet Explorer 8 y posteriores, WebKit, y Gecko). Sin embargo, la desventaja de este enfoque es que el desplegable de opciones sobresale en el lado derecho (por los 20 píxeles que ocultamos... porque los elementos option toman el ancho del elemento select).

introduzca la descripción de la imagen aquí

[It sin embargo, debe tenerse en cuenta que si el elemento custom select es necesario solo para dispositivos MOBILE, entonces el problema anterior no se aplica, debido a la forma en que cada teléfono abre el elemento select de forma nativa. Así que para móviles, esta puede ser la mejor solución.]

.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;
}
<div class="styled">
  <select>
    <option>Pineapples</option>
    <option selected>Apples</option>
    <option>Chocklate</option>
    <option>Pancakes</option>
  </select>
</div>

Si la flecha personalizada es necesaria en Firefox - antes de Versión 35 - pero no es necesario apoyar las versiones antiguas de IE - a continuación, seguir leyendo...

Solución # 3 - Utilice la propiedad pointer-events ( Demo )

(Leer más aquí)

La idea aquí es superponer un elemento sobre la flecha desplegable nativa (para crear nuestra personalizada) y luego rechazar eventos de puntero en él.

Ventaja: Funciona bien en WebKit y Gecko. También se ve bien (no hay elementos sobresalientes option)

Desventaja: Internet Explorer (IE10 y abajo) no es compatible con pointer-events, lo que significa que no puede hacer clic en la flecha personalizada. Además, otra desventaja (obvia) con este método es que no puede apuntar a su nueva imagen de flecha con un efecto de hover o cursor de mano, ¡porque acabamos de deshabilitar los eventos de puntero en ellos!

Sin embargo, con este método puede usar Modernizador o comentarios condicionales para hacer que Internet Explorer vuelva a la flecha incorporada estándar.

NB: {[31] } Siendo que Internet Explorer 10 ya no es compatible con conditional comments: Si desea usar este enfoque, probablemente debería usar Modernizr . Sin embargo, todavía es posible excluir el CSS pointer-events de Internet Explorer 10 con un hack CSS descrito aquí.

.notIE {
  position: relative;
  display: inline-block;
}
select {
  display: inline-block;
  height: 30px;
  width: 150px;
  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;
  }
}
<!--[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]-->
 842
Author: Danield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-20 16:22:39

Es posible, pero desafortunadamente principalmente en navegadores basados en Webkit en la medida en que nosotros, como desarrolladores, lo requerimos. Aquí está el ejemplo del estilo CSS reunido desde el panel de opciones de Chrome a través del inspector de herramientas para desarrolladores incorporado, mejorado para que coincida con las propiedades CSS actualmente soportadas en la mayoría de los navegadores modernos:

select {
    -webkit-appearance: button;
    -moz-appearance: button;
    -webkit-user-select: none;
    -moz-user-select: none;
    -webkit-padding-end: 20px;
    -moz-padding-end: 20px;
    -webkit-padding-start: 2px;
    -moz-padding-start: 2px;
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: url(../images/select-arrow.png), -webkit-linear-gradient(top, #E5E5E5, #F4F4F4); /* For Chrome and Safari */
    background-image: url(../images/select-arrow.png), -moz-linear-gradient(top, #E5E5E5, #F4F4F4); /* For old Fx (3.6 to 15) */
    background-image: url(../images/select-arrow.png), -ms-linear-gradient(top, #E5E5E5, #F4F4F4); /* For pre-releases of IE 10*/
    background-image: url(../images/select-arrow.png), -o-linear-gradient(top, #E5E5E5, #F4F4F4); /* For old Opera (11.1 to 12.0) */ 
    background-image: url(../images/select-arrow.png), linear-gradient(to bottom, #E5E5E5, #F4F4F4); /* Standard syntax; must be last */
    background-position: center right;
    background-repeat: no-repeat;
    border: 1px solid #AAA;
    border-radius: 2px;
    box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
    color: #555;
    font-size: inherit;
    margin: 0;
    overflow: hidden;
    padding-top: 2px;
    padding-bottom: 2px;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Cuando ejecuta este código en cualquier página dentro de un navegador basado en Webkit, debe cambiar la apariencia del cuadro de selección, eliminar la flecha estándar del sistema operativo y agregar una flecha PNG, espaciado antes y después de la etiqueta, casi todo lo que quieras.

La parte más importante es la propiedad appearance, que cambia el comportamiento del elemento.

Funciona perfectamente en casi todos los navegadores basados en Webkit, incluidos los móviles, aunque parece que Gecko no es compatible con appearance así como con Webkit.

 219
Author: Matthew Morek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-10 18:34:07

El elemento select y su función desplegable son difíciles de estilizar.

atributos de estilo para el elemento select por Chris Heilmann confirma lo que Ryan Dohery dijo en un comentario a la primera respuesta:

" El elemento select es parte del sistema operativo, no el navegador chrome. Por lo tanto, es muy poco fiable para el estilo, y no necesariamente tiene sentido probar Por cierto."

 58
Author: pavium,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 16:41:04

La mayor inconsistencia que he notado al seleccionar estilos es Safari y Google Chrome renderizado (Firefox es totalmente personalizable a través de CSS). Después de algunas búsquedas a través de oscuras profundidades de Internet me encontré con lo siguiente, que resuelve casi por completo mis dudas con WebKit:

Safari y Google Chrome fix :

select {
  -webkit-appearance: none;
}

Esto, sin embargo, elimina la flecha desplegable. Puede agregar una flecha desplegable usando una flecha cercana div con un fondo, margen negativo o absolutamente posicionado sobre el menú desplegable select.

* Más información y otras variables están disponibles en Propiedad CSS: - webkit-apariencia.

 39
Author: ioTus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 00:03:43

<select> las etiquetas se pueden diseñar a través de CSS al igual que cualquier otro elemento HTML en una página HTML renderizada en un navegador. A continuación se muestra un ejemplo (demasiado simple) que colocará un elemento select en la página y mostrará el texto de las opciones en azul.

Archivo HTML de ejemplo (selectExample.html):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <title>Select Styling</title>
  <link href="selectExample.css" rel="stylesheet">
</head>
<body>
<select id="styledSelect" class="blueText">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="cherry">Cherry</option>
</select>
</body>
</html>

Archivo CSS de ejemplo (selectExample.css):

/* All select elements on page */
select {
  position: relative;
}

/* Style by class. Effects the text of the contained options. */
.blueText {
  color: #0000FF;
}

/* Style by id. Effects position of the select drop down. */
#styledSelect {
  left: 100px;
}
 36
Author: jeremyosborne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-06 18:49:00

Tuve este problema exacto, excepto que no podía usar imágenes y no estaba limitado por el soporte del navegador. Esto debería ser "según las especificaciones" y con suerte empezar a trabajar en todas partes eventualmente.

Utiliza capas de fondo giradas por capas para "cortar" una flecha desplegable, ya que los pseudo-elementos no funcionarían para el elemento select. Reemplace "hotpink" con su color favorito-yo uso una variable.

select {
  font: 400 12px/1.3 "Helvetica Neue", sans-serif;
  -webkit-appearance: none;
  appearance: none;
  border: 1px solid hotpink;
  line-height: 1;
  outline: 0;
  color: hotpink;
  border-color: hotpink;
  padding: 0.65em 2.5em 0.55em 0.75em;
  border-radius: 3px;
  background: linear-gradient(hotpink, hotpink) no-repeat,
              linear-gradient(-135deg, rgba(255,255,255,0) 50%, white 50%) no-repeat,
              linear-gradient(-225deg, rgba(255,255,255,0) 50%, white 50%) no-repeat,
              linear-gradient(hotpink, hotpink) no-repeat;
  background-color: white;
  background-size: 1px 100%, 20px 20px, 20px 20px, 20px 60%;
  background-position: right 20px center, right bottom, right bottom, right bottom;   
}
<select>
    <option>So many options</option>
    <option>...</option>
</select>
 17
Author: Henrik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-14 14:45:27

La entrada del blogCómo CSS formulario desplegable estilo sin JavaScript funciona para mí, pero falla en Opera aunque:

select {
    border: 0 none;
    color: #FFFFFF;
    background: transparent;
    font-size: 20px;
    font-weight: bold;
    padding: 2px 10px;
    width: 378px;
    *width: 350px;
    *background: #58B14C;
}

#mainselection {
    overflow: hidden;
    width: 350px;
    -moz-border-radius: 9px 9px 9px 9px;
    -webkit-border-radius: 9px 9px 9px 9px;
    border-radius: 9px 9px 9px 9px;
    box-shadow: 1px 1px 11px #330033;
    background: url("arrow.gif") no-repeat scroll 319px 5px #58B14C;
}

<div id="mainselection">
    <select>
    <option>Select an Option</option>
    <option>Option 1</option>
    <option>Option 2</option>
    </select>
</div>
 13
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 20:01:36

Aquí hay una versión que funciona en todos los navegadores modernos. La clave está usando appearance:none que elimina el formato predeterminado. Dado que todo el formato se ha ido, usted tiene que añadir de nuevo en la flecha que diferencia visualmente la selección de la entrada.

Ejemplo de trabajo: https://jsfiddle.net/gs2q1c7p /

select:not([multiple]) {
    -webkit-appearance: none;
    -moz-appearance: none;
    background-position: right 50%;
    background-repeat: no-repeat;
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);
    padding: .5em;
    padding-right: 1.5em
}

#mySelect {
    border-radius: 0
}
<select id="mySelect">
    <option>Option 1</option>
    <option>Option 2</option>
</select>
 12
Author: Eric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-01 20:27:54
select  {
    outline: 0;
    overflow: hidden;
    height: 30px;
    background: #2c343c;
    color: #747a80;
    border: #2c343c;
    padding: 5px 3px 5px 10px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 10px;
}

select option {border: 1px solid #000; background: #010;}
 10
Author: gecko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 19:57:42

Si el estilo es un problema importante, usar un widget completamente personalizado podría ayudar, como el descrito en la publicación del blog Reinventando un menú desplegable con CSS y jQuery.

 8
Author: Jayesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 20:02:57

En los navegadores modernos es relativamente indoloro diseñar el <select> en CSS. Con appearance: none la única parte difícil es reemplazar la flecha (si eso es lo que quieres). Aquí hay una solución que utiliza un URI inline data: con SVG de texto plano:

select {
  -moz-appearance: none;
  -webkit-appearance: none;
  appearance: none;
  
  background-repeat: no-repeat;
  background-size: 0.5em auto;
  background-position: right 0.25em center;
  padding-right: 1em;
  
  background-image: url("data:image/svg+xml;charset=utf-8, \
    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 60 40'> \
      <polygon points='0,0 60,0 30,40' style='fill:black;'/> \
    </svg>");
}
<select>
  <option>Option 1</option>
  <option>Option 2</option>
</select>

<select style="font-size: 2rem;">
  <option>Option 1</option>
  <option>Option 2</option>
</select>

El resto del estilo (bordes, relleno, colores, etc.) es bastante sencillo.

Esto funciona en todos los navegadores que acabo de probar (Firefox 50, Chrome 55, Edge 38 y Safari 10). Una nota sobre Firefox es que si si desea utilizar el carácter # en el URI de datos (por ejemplo, fill: #000), debe escaparlo (fill: %23000).

 8
Author: Kevin Christopher Henry,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-13 19:03:59

Llegué a tu caso usando Bootstrap. Esta es la solución más simple que funciona:

select.form-control {
    -moz-appearance: none;
    -webkit-appearance: none;
    appearance: none;
    background-position: right center;
    background-repeat: no-repeat;
    background-size: 1ex;
    background-origin: content-box;
    background-image: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMiIKICAgdmlld0JveD0iMCAwIDM1Ljk3MDk4MyAyMy4wOTE1MTgiCiAgIGhlaWdodD0iNi41MTY5Mzk2bW0iCiAgIHdpZHRoPSIxMC4xNTE4MTFtbSI+CiAgPGRlZnMKICAgICBpZD0iZGVmczQiIC8+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhNyI+CiAgICA8cmRmOlJERj4KICAgICAgPGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPgogICAgICAgIDxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PgogICAgICAgIDxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz4KICAgICAgICA8ZGM6dGl0bGU+PC9kYzp0aXRsZT4KICAgICAgPC9jYzpXb3JrPgogICAgPC9yZGY6UkRGPgogIDwvbWV0YWRhdGE+CiAgPGcKICAgICB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMjAyLjAxNDUxLC00MDcuMTIyMjUpIgogICAgIGlkPSJsYXllcjEiPgogICAgPHRleHQKICAgICAgIGlkPSJ0ZXh0MzMzNiIKICAgICAgIHk9IjYyOS41MDUwNyIKICAgICAgIHg9IjI5MS40Mjg1NiIKICAgICAgIHN0eWxlPSJmb250LXN0eWxlOm5vcm1hbDtmb250LXdlaWdodDpub3JtYWw7Zm9udC1zaXplOjQwcHg7bGluZS1oZWlnaHQ6MTI1JTtmb250LWZhbWlseTpzYW5zLXNlcmlmO2xldHRlci1zcGFjaW5nOjBweDt3b3JkLXNwYWNpbmc6MHB4O2ZpbGw6IzAwMDAwMDtmaWxsLW9wYWNpdHk6MTtzdHJva2U6bm9uZTtzdHJva2Utd2lkdGg6MXB4O3N0cm9rZS1saW5lY2FwOmJ1dHQ7c3Ryb2tlLWxpbmVqb2luOm1pdGVyO3N0cm9rZS1vcGFjaXR5OjEiCiAgICAgICB4bWw6c3BhY2U9InByZXNlcnZlIj48dHNwYW4KICAgICAgICAgeT0iNjI5LjUwNTA3IgogICAgICAgICB4PSIyOTEuNDI4NTYiCiAgICAgICAgIGlkPSJ0c3BhbjMzMzgiPjwvdHNwYW4+PC90ZXh0PgogICAgPGcKICAgICAgIGlkPSJ0ZXh0MzM0MCIKICAgICAgIHN0eWxlPSJmb250LXN0eWxlOm5vcm1hbDtmb250LXZhcmlhbnQ6bm9ybWFsO2ZvbnQtd2VpZ2h0Om5vcm1hbDtmb250LXN0cmV0Y2g6bm9ybWFsO2ZvbnQtc2l6ZTo0MHB4O2xpbmUtaGVpZ2h0OjEyNSU7Zm9udC1mYW1pbHk6Rm9udEF3ZXNvbWU7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjpGb250QXdlc29tZTtsZXR0ZXItc3BhY2luZzowcHg7d29yZC1zcGFjaW5nOjBweDtmaWxsOiMwMDAwMDA7ZmlsbC1vcGFjaXR5OjE7c3Ryb2tlOm5vbmU7c3Ryb2tlLXdpZHRoOjFweDtzdHJva2UtbGluZWNhcDpidXR0O3N0cm9rZS1saW5lam9pbjptaXRlcjtzdHJva2Utb3BhY2l0eToxIj4KICAgICAgPHBhdGgKICAgICAgICAgaWQ9InBhdGgzMzQ1IgogICAgICAgICBzdHlsZT0iZmlsbDojMzMzMzMzO2ZpbGwtb3BhY2l0eToxIgogICAgICAgICBkPSJtIDIzNy41NjY5Niw0MTMuMjU1MDcgYyAwLjU1ODA0LC0wLjU1ODA0IDAuNTU4MDQsLTEuNDczMjIgMCwtMi4wMzEyNSBsIC0zLjcwNTM1LC0zLjY4MzA0IGMgLTAuNTU4MDQsLTAuNTU4MDQgLTEuNDUwOSwtMC41NTgwNCAtMi4wMDg5MywwIEwgMjIwLDQxOS4zOTM0NiAyMDguMTQ3MzIsNDA3LjU0MDc4IGMgLTAuNTU4MDMsLTAuNTU4MDQgLTEuNDUwODksLTAuNTU4MDQgLTIuMDA4OTMsMCBsIC0zLjcwNTM1LDMuNjgzMDQgYyAtMC41NTgwNCwwLjU1ODAzIC0wLjU1ODA0LDEuNDczMjEgMCwyLjAzMTI1IGwgMTYuNTYyNSwxNi41NDAxNyBjIDAuNTU4MDMsMC41NTgwNCAxLjQ1MDg5LDAuNTU4MDQgMi4wMDg5MiwwIGwgMTYuNTYyNSwtMTYuNTQwMTcgeiIgLz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo=");
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<section class="container">
  <form class="form-horizontal">
    <select class="form-control">
      <option>One</option>
      <option>Two</option>
    </select>
  </form>
</section>

Nota: el material base64 es fa-chevron-down en SVG.

 8
Author: Yajo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-05 04:01:38

Use la propiedad clip para recortar los bordes y la flecha del elemento select, luego agregue sus propios estilos de reemplazo al envoltorio:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          select { position: absolute; clip:rect(2px 49px 19px 2px); z-index:2; }
          body > span { display:block; position: relative; width: 64px; height: 21px; border: 2px solid green;  background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }
        </style>
      </head>
      <span>
        <select>
          <option value="">Alpha</option>
          <option value="">Beta</option>
          <option value="">Charlie</option>
        </select>
      </span>
    </html>

Use una segunda selección con cero opacidad para hacer clickable el botón:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
          #real { position: absolute; clip:rect(2px 51px 19px 2px); z-index:2; }
          #fake { position: absolute; opacity: 0; }
    
          body > span { display:block; position: relative; width: 64px; height: 21px; background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }
        </style>
      </head>
      <span>
        <select id="real">
          <option value="">Alpha</option>
          <option value="">Beta</option>
          <option value="">Charlie</option>
        </select>
        <select id="fake">
          <option value="">Alpha</option>
          <option value="">Beta</option>
          <option value="">Charlie</option>
        </select>
      </span>
    </html>

Las coordenadas difieren entre Webkit y otros navegadores, pero un @media query puede cubrir eso.

Referencias

 7
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:57

Editar este elemento no es recomendable, pero si quieres probarlo es como cualquier otro elemento HTML.

Ejemplo de edición:

/*Edit select*/
select {
    /*css style here*/
}

/*Edit option*/
option {
    /*css style here*/
}

/*Edit selected option*/
/*element  attr    attr value*/
option[selected="selected"] {
    /*css style here*/
}

<select>
    <option >Something #1</option>
    <option selected="selected">Something #2</option>
    <option >Something #3</option>
</select>
 4
Author: Homar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-21 17:48:28

Un muy buen ejemplo que utiliza :after y :before para hacer el truco está en Cuadro de selección de estilo con CSS3 / CSSDeck

 4
Author: Ahmad Ajmi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 20:09:03

Sí. Puedes darle estilo a cualquier elemento HTML por su nombre de etiqueta, así:

select {
  font-weight: bold;
}

Por supuesto, también puede usar una clase CSS para darle estilo, como cualquier otro elemento:

<select class="important">
  <option>Important Option</option>
  <option>Another Important Option</option>
</select>

<style type="text/css">
  .important {
    font-weight: bold;
  }
</style>
 4
Author: Dave Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-26 00:31:27

Definitivamente deberías hacerlo como en Styling select, optgroup y opciones con CSS. En muchos sentidos, el color de fondo y el color son justo lo que normalmente necesitaría para las opciones de estilo, no toda la selección.

 3
Author: Otvazhnii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 20:06:58
label {
    position: relative;
    display: inline-block;
}
select {
    display: inline-block;
    padding: 4px 3px 5px 5px;
    width: 150px;
    outline: none;
    color: black;
    border: 1px solid #C8BFC4;
    border-radius: 4px;
    box-shadow: inset 1px 1px 2px #ddd8dc;
    background-color: lightblue;
}

Esto usa un color de fondo para seleccionar elementos y eliminé la imagen..

 3
Author: Lucky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-25 20:08:08

A partir de Internet Explorer 10, puede utilizar el ::-ms-expand selector de pseudo elemento para dar estilo y ocultar el elemento de flecha desplegable.

select::-ms-expand {
    display:none;
    /* or visibility: hidden; to keep it's space/hitbox */
}

El estilo restante debe ser similar a otros navegadores.

Aquí hay una bifurcación básica de jsfiddle de Danield que aplica soporte para IE10

 3
Author: Richard Szalay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-09 21:50:16

Aquí hay una solución basada en mis ideas favoritas de esta discusión. Esto permite diseñar un elemento directamente sin ningún marcado adicional.

Funciona IE10+ con un respaldo seguro para IE8/9. Una advertencia para estos navegadores es que la imagen de fondo debe estar posicionada y lo suficientemente pequeña como para esconderse detrás del control de expansión nativo.

HTML

<select name='options'>
  <option value='option-1'>Option 1</option>
  <option value='option-2'>Option 2</option>
  <option value='option-3'>Option 3</option>
</select>

SCSS

body {
  padding: 4em 40%;
  text-align: center;
}

select {
  $bg-color: lightcyan;
  $text-color: black;
  appearance: none; // using -prefix-free http://leaverou.github.io/prefixfree/
  background: {
    color: $bg-color;
    image: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/1255/caret--down-15.png");
    position: right;
    repeat: no-repeat;
  }
  border: {
    color: mix($bg-color, black, 80%);
    radius: .2em;
    style: solid;
    width: 1px;
    right-color: mix($bg-color, black, 60%);
    bottom-color: mix($bg-color, black, 60%);
  }
  color: $text-color;
  padding: .33em .5em;
  width: 100%;
}

// Removes default arrow for IE10+
// IE 8/9 get dafault arrow which covers caret image
// as long as caret image is small than and positioned
// behind default arrow
select::-ms-expand {
    display: none;
}

Codepen

Http://codepen.io/ralgh/pen/gpgbGx

 3
Author: ralgh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-29 13:50:37

Hay una manera de estilizar las etiquetas SELECT.

Si hay un parámetro "size" en la etiqueta, se aplicará casi cualquier CSS. Usando este truco, he creado un violín que es prácticamente equivalente a una etiqueta select normal, además el valor se puede editar manualmente como un ComboBox en lenguajes visuales (a menos que pongas readonly en la etiqueta de entrada).

Así que aquí hay un ejemplo mínimo para ver el principio detrás:
(necesitarás jQuery para hacer clic mecanismo):

<style>

    /* only these 2 lines are truly required */
    .stylish span {position:relative;}
    .stylish select {position:absolute;left:0px;display:none}

    /* now you can style the hell out of them */
    .stylish input    { ... }
    .stylish select   { ... }
    .stylish option   { ... }
    .stylish optgroup { ... }

</style>
...
<div class="stylish">
    <label> Choose your superhero: </label>
    <span>
        <input onclick="$(this).closest('div').find('select').slideToggle(110)">
        <br>
        <select size=15 onclick="$(this).hide().closest('div').find('input').val($(this).find('option:selected').text());">

            <optgroup label="Fantasy"></optgroup>
            <option value="gandalf">Gandalf</option>
            <option value="harry">Harry Potter</option>
            <option value="jon">Jon Snow</option>

            <optgroup label="Comics"></optgroup>
            <option value="tony">Tony Stark</option>
            <option value="steve">Steven Rogers</option>
            <option value="natasha">Natasha Romanova</option>

        </select>
    </span>
</div>

Aquí está el violín con algunos estilos más: https://jsfiddle.net/dkellner/7ac9us70 /

(Es exagerado, por supuesto, solo para demostrar las posibilidades.)

Observe cómo las etiquetas no encapsulan las opciones que pertenecen debajo de ellas como normalmente deberían; sí, esto es intencional, es para el estilo. (La manera bien educada sería mucho menos estilable.) Y sí que funcionan perfectamente bien de esta manera.

Antes de que alguien apunte fuera de la parte NO-JS: Sé que la pregunta decía "no Javascript". Para mí, esto es más como por favor, no te molestes con los plugins, sé que pueden hacerlo, pero necesito la forma nativa. Entendido, sin plugins, sin scripts adicionales incluidos, solo lo que cabe dentro del "onclick"de una etiqueta. La única dependencia es jQuery, para evitar el "documento nativo".parentNode.getElementsByTagName" la locura. Pero puede funcionar de esa manera. Así que sí, esta es una etiqueta de selección nativa con estilo nativo y algunos controladores onclick. Es claramente no es "una solución Javascript".

Disfrute!

 2
Author: dkellner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-12 11:56:59

El segundo método en la respuesta de Danield ( https://stackoverflow.com/a/13968900/280972 ) se puede mejorar para trabajar con hover-effects y otros eventos del ratón. Solo asegúrese de que el elemento"button" viene justo después del elemento select en el marcado. A continuación, apunte con el selector + css:

HTML:

<select class="select-input">...</select>
<div class="select-button"></div>

CSS:

.select-input:hover+.select-button {
    [hover styles here]
}

Esto, sin embargo, mostrará el efecto hover cuando se desplaza sobre el elemento select, no solo sobre el "botón".

Estoy usando este método en combinación con Angular (ya que mi proyecto resulta ser una aplicación Angular de todos modos), para cubrir todo el select-element, y dejar que Angular muestre el texto de la opción seleccionada en el "botón"-elemento. En este caso, tiene mucho sentido que el efecto hover se aplique al pasar el cursor por encima de la selección. Sin embargo, no funciona sin javascript, por lo que si desea hacer esto, y su sitio tiene que funcionar sin javascript, debe asegurarse de que su script agregue los elementos y clases necesarias para la mejora. De esa manera, un navegador sin javascript simplemente obtendrá una selección normal, sin estilo, en lugar de una insignia con estilo que no se actualiza correctamente.

 1
Author: Adrian Schmidt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:51

También puede agregar un estilo de desplazamiento al menú desplegable.

select {position:relative; float:left; width:21.4%; height:34px; background:#f9f9e0; border:1px solid #41533f; padding:0px 10px 0px 10px; color:#41533f; margin:-10px 0px 0px 20px; background: transparent; font-size: 12px; -webkit-appearance: none; -moz-appearance: none; appearance: none; background: url(https://alt-fit.com/images/global/select-button.png) 100% / 15% no-repeat #f9f9e0;}
select:hover {background: url(https://alt-fit.com/images/global/select-button.png) 100% / 15% no-repeat #fff;}
<html>
<head>
</head>
<body>
<select name="type" class="select"><option style="color:#41533f;" value="Select option">Select option</option>
<option value="Option 1">Option 1</option>
<option value="Option 2">Option 2</option>
<option value="Option 3">Option 3</option>
</select>
</body>
</html>
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-02 11:02:53

Una solución solo CSS y HTML

Parece compatible con Chrome, Firefox e IE11. Pero por favor deje sus comentarios sobre otros navegadores web.

Como sugiere la respuesta de @Danield, envuelvo mi selección en un div (incluso dos divs para compatibilidad con x-browser) para obtener el comportamiento esperado.

Véase http://jsfiddle.net/bjap2 /

HTML:

<div class="sort-options-wrapper">
    <div class="sort-options-wrapper-2">
        <select class="sort-options">
                <option value="choiceOne">choiceOne</option>
                <option value="choiceOne">choiceThree</option>
                <option value="choiceOne">choiceFour</option>
                <option value="choiceFiveLongTestPurpose">choiceFiveLongTestPurpose</option>
        </select>
    </div>
    <div class="search-select-arrow-down"></div>
</div>

Observe las 2 envolturas div. También observe el div adicional agregado para colocar el botón de flecha hacia abajo en cualquier lugar te gusta (posicionado absolutamente), aquí lo ponemos a la izquierda.

CSS

.sort-options-wrapper {
    display: inline-block;
    position: relative;
    border: 1px solid #83837f;
}
/* this second wrapper is needed for x-browser compatibility */
.sort-options-wrapper-2 {
    overflow: hidden;
}
select {
    margin-right: -19px; /* that's what hidding the default-provided browser arrow */
    padding-left: 13px;
    margin-left: 0;
    border: none;
    background: none;
    /* margin-top & margin-bottom must be set since some browser have default values for select elements */
    margin-bottom: 1px;
    margin-top: 1px;
}
select:focus {
    outline: none; /* removing default browsers outline on focus */
}
.search-select-arrow-down {
    position: absolute;
    height:10px;
    width: 12px;
    background: url(http://i.imgur.com/pHIYN06.png) scroll no-repeat 2px 0px;
    left: 1px;
    top: 5px;
}
 0
Author: Adrien Be,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-07 08:47:55