Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict the width of html dropdown options list

Tags:

html

jquery

css

I want to restrict the html drpodown option-list width by giving text-overflow:ellipsis like below:

+------------------+
| Please Select    |
+------------------+
| Long Descrip.... |
| Short Descr      |
| Long Descrip.... |
+------------------+

I tried this by giving

select option{max-width: 100px;text-overflow:ellipsis}

Only the dropdown width is getting reduced where as not the option width. I might be missing basic attributes to do this. But I couldn't figure it out. Can anyone suggest on this..

like image 509
Sriks Avatar asked Dec 12 '25 15:12

Sriks


2 Answers

The width of the dropdown options panel itself is controlled by the browser chrome and as such cannot be affected by javascript.

If you need to change the appearance of the dropdown, you will need to use a plugin which transposes the select element to HTML elements which can be controlled, such as Select2

like image 160
Rory McCrossan Avatar answered Dec 14 '25 15:12

Rory McCrossan


You could try that:

var $select = $('select');
$select.find('option').each(function () {
    var _tmp = $('<span/>', {
        html: this.innerHTML
    }).css({
        position: 'absolute',
        top: -9999,
        left: -9999
    }).appendTo('body');
    var width = _tmp.width();
    var maxWidth = $select.width();
    while (_tmp.width() > maxWidth) {
        _tmp.text(function (index, text) {
            return text.replace(/\W*\s(\S)*$/, '...');
        });
    }
    this.innerHTML = _tmp.text();
    _tmp.remove();
});

--DEMO--

But Rory's answer is usually the way to go, avoiding any headhache regarding cross browser support.

like image 42
A. Wolff Avatar answered Dec 14 '25 17:12

A. Wolff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!