Home >Web Front-end >CSS Tutorial >How to Control the Width of Select Box Options and Implement Text Ellipsis?

How to Control the Width of Select Box Options and Implement Text Ellipsis?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 17:45:29425browse

How to Control the Width of Select Box Options and Implement Text Ellipsis?

Controlling the Width of Select Box Options

In HTML, by applying style attributes to both the select element and its child option elements, it's possible to specify the width of each option to ensure it matches the select box width. However, achieving this with CSS alone may not be sufficient.

One solution involves incorporating JavaScript to further control the option width and enable text ellipsis when necessary. The provided JavaScript code introduces a shortString function that dynamically adjusts the text within option elements having the .short class and the data-limit attribute.

Here's how to implement this solution:

<code class="html"><!-- HTML -->
<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></code>
<code class="css"><!-- CSS -->
select {
  width: 250px;
}

option {
  width: 250px;
}</code>
<code class="js"><!-- JavaScript -->
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');
};</code>

This approach ensures that the option width is identical to the select box width, and when the option text exceeds the specified limit, the excess text is replaced with an ellipsis.

The above is the detailed content of How to Control the Width of Select Box Options and Implement Text Ellipsis?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn