I am trying to make the Select Option to have the width of the current Selected Option.
My code is the standard HTML for a Select Option dropdown:
<select name="search_options">
<option value="all">All</option>
<option value="entertainment">Entertainment</option>
<option value="newsandpolitics">News & Politics</option>
<option value="sports">Sports</option>
<option value="lifestyle">Lifestyle</option>
<option value="health">Health</option>
<option value="scienceandtech">Science & Tech</option>
</select>
I have been trying to do this with just CSS or Javascript, with no JQuery, and I can't figure it out.
I have found several fiddles with JQuery already, but no CSS/Javascript ones.
Is there any way to achieve this, identical with the above 2 fiddles, using just CSS or pure Javascript?
Any pointers in the right direction would be great.
I wrote this answer for a different thread which just got closed as a duplicate of this one. The problem with these answers is they are a bit complex and use hard-coded padding values, which can be unreliable. Here is my solution which doesn't require anything hard-coded.
While there isn't a CSS and HTML only way, a fairly straight-forward way to do it is to create a hidden select, set its only option to the chosen value, and the take that width and set it to the visible select.
The dummy select is basically just a reliable method for measuring how wide it should be.
Add that logic to "change" and it should be good and manually trigger it once, then you should be good.
Converting to JavaScript and explaining your first example (http://jsfiddle.net/5AANG/4/).
This creates a temporary
<span>
element and copies the styles from the select box to the span. Then it measures the width of the span, sets the width of the select box based on that width, and removes the span from the document.In plain old JavaScript:
Grab all the
<select>
s:Add our event listener (defined below) to each:
Define the event listener:
Base variable definitions:
Set the content of our temporary span (
s
) to the content of the selected option:The fun part! Assigning to the
<span>
the styles of the selected option. (SeegetComputedStyle
)Append the span to the document so we can grab its width:
Set the
<select>
's width based on the span's width (30 is a magic number pulled from the above mentioned fiddle).Quick! Remove the temporary span before anybody sees it!
Demo: https://jsfiddle.net/Hatchet/a0xzz6mf/
Based on your second link you can do it like this:
Test: http://jsfiddle.net/ndquxquu/