Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG inside OPTION element

I am creating the following svg element and structure:

<svg width="135" height="15">
    <rect width="15" height="15" fill="#ffffe5" x="0" y="0"></rect>
    <rect width="15" height="15" fill="#f7fcb9" x="15" y="0"></rect>
    <rect width="15" height="15" fill="#d9f0a3" x="30" y="0"></rect>
    <rect width="15" height="15" fill="#addd8e" x="45" y="0"></rect>
    <rect width="15" height="15" fill="#78c679" x="60" y="0"></rect>
    <rect width="15" height="15" fill="#41ab5d" x="75" y="0"></rect>
    <rect width="15" height="15" fill="#238443" x="90" y="0"></rect>
    <rect width="15" height="15" fill="#006837" x="105" y="0"></rect>
    <rect width="15" height="15" fill="#004529" x="120" y="0"></rect>
</svg>

Which produces a row of little squares. Just like this:

enter image description here

So far everything is OK.

Then I place the code above inside an option for the select drop-down, as shown below:

<select id="data-color-scheme">
    <option id="YlGn">
        <div>
            <svg width="135" height="15">
                <rect width="15" height="15" fill="#ffffe5" x="0" y="0"></rect>
                <rect width="15" height="15" fill="#f7fcb9" x="15" y="0"></rect>
                <rect width="15" height="15" fill="#d9f0a3" x="30" y="0"></rect>
                <rect width="15" height="15" fill="#addd8e" x="45" y="0"></rect>
                <rect width="15" height="15" fill="#78c679" x="60" y="0"></rect>
                <rect width="15" height="15" fill="#41ab5d" x="75" y="0"></rect>
                <rect width="15" height="15" fill="#238443" x="90" y="0"></rect>
                <rect width="15" height="15" fill="#006837" x="105" y="0"></rect>
                <rect width="15" height="15" fill="#004529" x="120" y="0"></rect>
            </svg>
        </div>
    </option>
</select>

Now the content of the option is displayed as a white blank, as shown in the image below:

enter image description here

As you can see, the content of the image is empty. However, if I run the debugging inspector, I can still detect the svg element there.

What am I doing wrong? How can I display an svg inside an option? Thanks.

like image 369
Greeso Avatar asked Oct 05 '17 23:10

Greeso


1 Answers

HTML <option> elements can only contain plain text.

What you are running into is the long-running "How to style a <select> element" discussion. To describe all the possible hacks and solutions proposed through the years goes far beyond the scope of an answer here and would be purely opinion-based. Look around for

  • CSS hacks that try to override the OS-provided styling
  • UI modules for Javascript libraries that emulate the behavior of <select> with other elements
  • Web Components

and make up your own mind.

like image 184
ccprog Avatar answered Sep 16 '22 19:09

ccprog