Dave Dave - 4 months ago 15
CSS Question

Is there a CSS way to automatically set the width of an element based on the size of text strings?

I’m creating a styled select menu in which I’m styling an unordered list that is replacing my select element.

<div class="select">
<select name="distance" id="distance" class="select-hidden">
<option value="5.0 5"><font><font>5 mi</font></font></option>
<option value="6.0 4">6 km</option>
<option value="10.0 4" selected="selected"><font><font>10 km</font></font></option></select><div class="select-styled">10 km</div><ul class="select-options" style="display: none;"><li rel="5.0 5"><font><font>5 mi</font></font></li><li rel="6.0 4"><font><font>6 km</font></font></li><li rel="10.0 4"><font><font>10 km</font></font></li></ul>

I then have this style

.select {
cursor: pointer;
display: inline-block;
position: relative;
font-size: 16px;
color: #000000;
width: 220px;
height: 42px;

Right now I’m hard-coding the width (220px) and my question is can I build this in a less rigid way such that the width will automatically be the width of the longest element name? Here is the Fiddle that illustrates my dilemma — https://jsfiddle.net/n73ao02h/13/ .


How about that: https://jsfiddle.net/n73ao02h/14/

A select-box without any width will always style according to its options. So we use that...

First step is to remove the fixed width.
We get the width in JS before we add display:none to it.
We then generate a temporary element styled-select with zeri width to automatically get the padding defined in CSS without hardcoding it.

We then have all we need to calculate the new width of your styled select-box:

    /* ... */
    var $paddingCalculator = $('<div />', {
        'class' : "select-styled test"
        width : 0,
        visibility : "hidden"
    var paddingWidth = $paddingCalculator.outerWidth();

    var selectWidth = $this.width() + paddingWidth;

    if ( !$this.parent().hasClass('select') ) {
        var $wrapper = $("<div />", {
            'class' : "select"
            width : selectWidth
        $this.wrap( $wrapper );
    }   // if
    /* ... */