JSFiddle - React, Tailwind, and code Playground
HTML
<select class="my-select" style="width: 170px;">
<option value="1" selected>Option 1</option>
<option value="2" selected>Option 2 longer</option>
<option value="3" selected>Options 3 longest of all</option>
</select>
CSS
.my-select{
font-size: 1rem;
color: rgb(80, 80, 80);
background: rgb(250, 250, 250);
border: 1px solid black;
outline: none;
-webkit-appearance: none;
}
.my-select::-ms-expand { /* To not show dropdown arrow in IE, Opera etc */
display: none;
}
JavaScript
var inputFields = document.querySelectorAll(".my-select");
// Resize on initial load
inputFields.forEach(function(element) {
element.addEventListener("change", function() {
resizeSelect(element);
});
});
function resizeSelect(sel) {
let tempOption = document.createElement('option');
tempOption.textContent = sel.options[sel.selectedIndex].textContent;
let tempSelect = document.createElement('select');
tempSelect.style.visibility = "hidden";
tempSelect.style.position = "fixed"
tempSelect.appendChild(tempOption);
sel.after(tempSelect);
sel.style.width = (parseInt(window.getComputedStyle(tempSelect).width)) + 'px';
alert(window.getComputedStyle(tempSelect).width);
tempSelect.remove();
}