Skip to content Skip to sidebar Skip to footer

Html Dropdown Auto-width Adjust

I've created a dropdown that has issues resizing according to what's selected. I'm using the following stackoverflow answer as inspiration to resize my dropdown: https://stackoverf

Solution 1:

the problem is your hidden dropdown has diff font size. add font-size: 16px; to #width_tmp_select and should work now.

$(document).ready(function() {
  $('.dropdown').change(function(){
    $("#width_tmp_option").html($('.dropdown option:selected').text()); 
    $(this).width($("#width_tmp_select").width());  
  });
});
.dropdown {
  width: 280px;
  overflow: hidden;
  background: url(https://secure.echobox.com/img/dropdown_arrow.png) no-repeat right transparent;
  border: 1px solid black;
  white-space: nowrap;
  background-size: 18px5px;
}

.dropdown select {
  width: 100%;
  background: transparent;
  font-size: 16px;
  border: 0;
  border-radius: 0;
  -webkit-appearance: none;
  -moz-appearance: none;
  font-family: "proxima-nova", Helvetica, Arial, sans-serif;
  white-space: nowrap;
  color: #56646E;
}

#width_tmp_select{
  display : none;
	font-size: 16px;
} 
<scriptsrc="https://code.jquery.com/jquery-3.1.1.min.js"integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="crossorigin="anonymous"></script><h2>
This "custom" dropdown doesn't resize correctly.
</h2><divclass="dropdown"><selectid="real_dropdown"><optiondisabled="">Options</option><optionvalue="long">Something super long in here</option><optionvalue="short">Short</option></select></div><selectid="width_tmp_select"><optionid="width_tmp_option"></option></select>

Solution 2:

With CSS my friend!! Please rep me :)

#real_dropdown {
  width: 100px;
  min-width: 100px;
  max-width: 200px;
}
#width_tmp_select {
  width: 100px;
  min-width: 100px;
  max-width: 200px;
}

Post a Comment for "Html Dropdown Auto-width Adjust"