6

Pretty self explaining, I need to style the option that is selected by the user. Is this possible without javascript?

Simple example:

HTML:

<select multiple>
    <option class="opt1" value="">Option 1</option>
    <option class="opt2" value="">Option 2</option>
</select>

CSS:

.opt1[selected]{
    background-color: red;
}
.opt2{
    background-color: green;
}

JS Fiddle Example

AlexG
  • 5,649
  • 6
  • 26
  • 43
  • http://www.w3schools.com/cssref/sel_attribute_value.asp – maioman May 12 '15 at 10:06
  • 2
    This link would help you http://stackoverflow.com/questions/8619406/css-selected-pseudo-class-similar-to-checked-but-for-for-select-elements – Sagar May 12 '15 at 10:09
  • Doesn't look as though there is a :selected css tag https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes – ste-fu May 12 '15 at 10:13
  • @Sagar Oh thanks, I've seen this post already today, but understood it the wrong way I did use `:selected` but did not try `:checked`, because I thought its only for radios/checkboxes – AlexG May 12 '15 at 10:17

2 Answers2

7

try this .

.your-select option:checked {
    background:#333;padding:20px;width:100px;border:3px solid #F00
}
<select multiple class="your-select">
    <option class="opt1" value="">Option 1</option>
    <option class="opt2" value="">Option 2</option>
 </select>
WasiF
  • 26,101
  • 16
  • 120
  • 128
Danin Na
  • 409
  • 1
  • 3
  • 13
1

https://css-tricks.com/the-checkbox-hack/

This article explains how to style an element by clicking on it with just css.

The idea is that you put a hidden input next to a div, and style the div based on it's neighboring input being checked.

Here's the example:

html

<label for="toggle-1">Do Something</label>
<input type="checkbox" id="toggle-1">
<div>Control me</div>

css

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
   /* For mobile, it's typically better to position checkbox on top of clickable
      area and turn opacity to 0 instead. */
}

/* Default State */
div {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
}

/* Toggled State */
input[type=checkbox]:checked ~ div {
   background: red;
}
NachoDawg
  • 1,533
  • 11
  • 21
  • I've found my answer in the comments above, but this seems to get handy in the future, thanks! – AlexG May 12 '15 at 10:19