How can I set the width of select box options?
Asked Answered
L

6

41

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/

Lugworm answered 17/4, 2016 at 12:47 Comment(2)
I don't think you can. Check this out: #1895976. For styling dropdowns, I suggest trying select2.github.ioDonaldson
@SideriteZackwehdex, At last, I come up with the solution by creating Custom Drop-down using ul, li. You can check my own answer, Any suggestion would be appropriated.Lugworm
A
16

I tried to find a solution through CSS. But I failed to do it. Doesn't matter; I have written a simple Javascript code for it. This can do 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>
Adjacency answered 17/4, 2016 at 15:34 Comment(1)
Not that bad but I come up with the solution by creating Custom Drop-down using ul, li. You can check my own answer, Any suggestion would be appropriated.Lugworm
F
5

You can use javascript to make the length of the option text to be less so as that it matches the length of the option. I found no solution for only using css

var e=document.querySelectorAll('option')
e.forEach(x=>{
if(x.textContent.length>20)
x.textContent=x.textContent.substring(0,20)+'...';
})
select
{
width:160px;
}
<select>
<option>fwefwefwefwe</option>
<option>fwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwefwe</option>
</select>
Flavor answered 29/1, 2020 at 6:25 Comment(1)
Nice and simple and just what I was looking for (outputting country names via Countries Rest API).Bypass
L
1

At last, I come up with the solution by creating Custom Drop-down using ul, li. Here is the solution:

FIDDLE DEMO

HTML

 $(document).ready(function (){
  $("div.selected").on("click", function () {
      var hasActiveClass = $("div.select-box").hasClass("active");

      if (hasActiveClass === false) {
          var windowHeight = $(window).outerHeight();
          var dropdownPosition = $(this).offset().top;
          var dropdownHeight = 95; // dropdown height

          if (dropdownPosition + dropdownHeight + 50 > windowHeight) {
              $("div.select-box").addClass("drop-up");
          }
          else {
             $("div.select-box").removeClass("drop-up");
          }

          var currentUniversity = $(this).find('text').text().trim();

          $.each($("ul.select-list li"), function () {
              var university = $(this).text().trim();
              if (university === currentUniversity)
                  $(this).addClass("active");
              else
                  $(this).removeClass("active");
          });
      }

      $("div.select-box").toggleClass("active");
  });

  $("ul.select-list li").on("click", function () {
      var university = $(this).html();
      $("span.text").html(university);
      $("div.select-box").removeClass("active");
  });

  $("ul.select-list li").hover(function () {
      $("ul.select-list li").removeClass("active");
  });

  $(document).click(function (event) {
      if ($(event.target).closest("div.custom-select").length < 1) {
          $("div.select-box").removeClass("active");
      }
  });

});
div.custom-select 
{
    height: 40px;
    width: 400px;
    position: relative;
    background-color: #F2F2F2;
    border: 1px solid #E4E4E4;
}

div.selected
{
    width: inherit;
    cursor: pointer;
    line-height: 20px;
    display: inline-block;
}

div.selected > .text
{
    padding: 10px;
    display: block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

div.select-box
{
    display: none;
    width: 100%;
    z-index: 10029;
    position: absolute;
    border-radius: 3px;
    box-shadow: 0 8px 20px #000000;
    box-shadow: 0 8px 20px rgba(0,0,0,.35)
}

div.select-box.active
{
    display: block;
}

div.select-box.drop-up
{
    top: auto;
    bottom: 100%;
}

ul.select-list
{
    margin: 0;
    padding: 10px;
    list-style-type: none;
}

ul.select-list li
{
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

ul.select-list li:hover,
ul.select-list li.active
{
    background-color: #999999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='custom-select'>
    <div class="selected">
       <span class='text'>Select</span>
    </div>
    <div class='select-box'>
       <ul class='select-list'>
          <li data-row='0' data-value=''>
              Select
          </li>
          <li data-row='1' data-value='BUET'>
              Bangladesh University of Engineering and Technology
          </li>
          <li data-row='2' data-value='MBSTU'>
              Mawlana Bhashani Science and Technology University
          </li>
       </ul>
    </div>
</div>
Lugworm answered 2/6, 2016 at 20:37 Comment(0)
M
1

Another simple jquery solution is to rewrite the option's length manually to get the wanted size as follow :

$('option').each(function() {
  var optionText = this.text;
  var newOption = optionText.substring(0, 36);
  $(this).text(newOption + '...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<select style="width:250px">
    <option>Select your University</option>
    <option>Bangladesh University of Engineering and Technology</option>
    <option>Mawlana Bhashani Science and Technology University</option>
</select>
Muimuir answered 10/1, 2019 at 12:32 Comment(0)
P
1

If you don't mind using jQuery, here is a simple solution. Just run it at the beginning of your code and it's applicable to every select

$('select').change(function(){
  var text = $(this).find('option:selected').text()
  var $aux = $('<select/>').append($('<option/>').text(text))
  $(this).after($aux)
  $(this).width($aux.width())
  $aux.remove()
}).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
  <option>Select your University</option>
  <option>Bangladesh University of Engineering and Technology</option>
  <option>Mawlana Bhashani Science and Technology University</option>
</select>
Pinder answered 15/12, 2021 at 21:32 Comment(1)
I think you're doing thinks backward here. The question was about setting the width of the options, not the select element.Prisage
P
0

This may be a little late, but I found that using CodeIgniter's word_limiter() function may do what you need, for example:

<option><?php echo word_limiter("Bangladesh University of Engineering and Technology",1); ?></option>

If you're not using CodeIgniter, you may just look up the function.

Hope this helps!

Petaliferous answered 14/9, 2022 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.