Sriks
Sriks

Reputation: 1699

How to restrict the width of html dropdown options list

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..

Upvotes: 2

Views: 1849

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

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.

Upvotes: 5

Amit
Amit

Reputation: 1919

This will help you

HTML

<select>
    <option>asd as das das dasdasdsadasdas asd</option>
    <option>asd as das das dasdasdsadasdas asd</option>
    <option>asd as das das dasdasdsadasdas asd</option>
    <option>asd as das das dasdasdsadasdas asd</option>
</select>

CSS

select{
    width:100px;
}
select option{
    width:100px;
}

Demo

Upvotes: -1

Rory McCrossan
Rory McCrossan

Reputation: 337580

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

Upvotes: 6

Related Questions