Styling option tags

2019-06-22 08:14发布

问题:

I have a drop down that contains options. I would like to partially break & bold some text as well as insert context breaks. I tried using CSS as well as HTML tags but I'm unable to get it. Can someone please suggest a solution? Thanks in advance

回答1:

I know this question is a bit old (or not new at least), but I'd like to show a very simple way to emulate a select element rather than using a "replacement plugin" as suggested in How to style the option of a html “select”?.

There are probably many, MANY ways to do this, but I try to keep things extremely simple, so my method of emulation only uses CSS. It is rather bare bones, but I'd like to point out that it is not a complicated thing to do so you might not need a plug in to do it.

Note1: Instead of using <option>, I used <label>. Since <label> is an interactive element, putting something interactive inside (like a <button>) would probably mess it up. Options are normally non-interactive anyway, but just be aware that this simple emulation can't do everything.

Note2: If you want to be able to select multiple options, just do a search for "radio" and replace with "checkbox".


Emulating Select Using Radio - No Collapse

input[type="radio"] {
  display: none;
}

input[type="radio"]:checked + label {
  background-color: black;
  color: #28AADC;
}

/* none functional styles.  just regular styling */
.radio_select {
  background-color: #28AADC;
  display: inline-block;
}
<div class="radio_select">
  <div>
    <input id="rad1" type="radio" name="radio_select" />
    <label for="rad1">Option 1</label>
  </div>

  <div>
    <input id="rad2" type="radio" name="radio_select" checked="checked" />
    <label for="rad2">Option 2</label>
  </div>
  
  <div>
    <input id="rad3" type="radio" name="radio_select" />
    <label for="rad3">Option 3</label>
  </div>
</div>


Radio select emulation - with collapse

Note: this won't work for mobile devices since it uses :hover.

input[type="radio"] {
  display: none;
}

/* style this to your heart's content */

input[type="radio"] + label {
  display: none;
}

input[type="radio"]:checked + label {
  background-color: black;
  color: #28AADC;
  display: inline-block;
}

.radio_select:hover label {
  display: inline-block;
}


/* none functional styles.  just regular styling */

.radio_select {
  background-color: #28AADC;
  display: inline-block;
}
<!-- NOTE:  This technique uses hover, so it won't work for mobile devices.
  I couldn't think of a pure CSS way to solve that.  Sorry. -->

<div class="radio_select">
  <div>
    <input id="rad1" type="radio" name="radio_select" />
    <label for="rad1">Option 1</label>
  </div>

  <div>
    <input id="rad2" type="radio" name="radio_select" />
    <label for="rad2">Option 2</label>
  </div>

  <div>
    <input id="rad3" type="radio" name="radio_select" checked="checked" />
    <label for="rad3">Option 3</label>
  </div>
</div>