How can I set the width of select box options?

I tried to find a solution from CSS. But I failed to do it. Doesn’t matter, I have written a simple javascript code for it. This is can do it something for it.

function shortString(selector) {
  const elements = document.querySelectorAll(selector);
  const tail="...";
  if (elements && elements.length) {
    for (const element of elements) {
      let text = element.innerText;
      if (element.hasAttribute('data-limit')) {
        if (text.length > element.dataset.limit) {
          element.innerText = `${text.substring(0, element.dataset.limit - tail.length).trim()}${tail}`;
        }
      } else {
        throw Error('Cannot find attribute \'data-limit\'');
      }
    }
  }
}

window.onload = function() {
  shortString('.short');
};
select {
  width: 250px;
}

option {
  width: 250px;
}
<select name="select" id="select">
  <option class="short" data-limit="37" value="Select your University">Select your University</option>
  <option class="short" data-limit="37" value="Bangladesh University of Engineering and Technology">Bangladesh University of Engineering and Technology</option>
  <option class="short" data-limit="37" value="Mawlana Bhashani Science and Technology University">Mawlana Bhashani Science and Technology University</option>
</select>

Leave a Comment