Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

css - Set Width at Option of Select Box

enter image description here

In the picture, the width of option is larger than the select box. I want to set width of those options as same as select box & for those larger options set text-overflow as ellipsis. Any help would be appreciated.

Here is what I tried:

Html

<select>
    <option>Select your University</option>
    <option>Bangladesh University of Engineering and Technology</option>
    <option>Mawlana Bhashani Science and Technology University</option>
</select>

Css

select, option {
    width: 250px;
}

option {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

Fiddle: https://jsfiddle.net/3bsbcqfz/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...