Select width auto css

Установить ширину выпадающего элемента в вариантах выпадающего списка HTML

Я работаю над сайтом, который включает автоматическое заполнение окна выбора с помощью PHP script. Все это прекрасно работает, но проблема заключается в том, что то, что я использую для заполнения текстового поля, имеет очень длинные заголовки (это статьи журналов и заголовки презентаций). Выпадающий квадрат простирается до ширины самого длинного элемента, который простирается от края экрана, поэтому сделать полосу прокрутки невозможно. Я пробовал различные методы, пытаясь вручную установить раскрывающийся список с помощью CSS на определенную ширину, но до сих пор безрезультатно. Лучшее, что я сделал, чтобы установить поле «Выбор» на определенную ширину, но выпадающее меню само по себе намного шире.

Любые советы по этому поводу будут очень признательны.

Оказывается, что следующая строка CSS работает во всех основных браузерах, кроме Google Chrome (это то, что я тестировал в этой странице). Если решение для Chrome известно, об этом было бы полезно узнать.

ОТВЕТЫ

Ответ 1

Вы можете стилизовать (хотя и с некоторыми ограничениями) фактические элементы с помощью селектора option :

Таким образом вы не только сдерживаете раскрывающийся список, но и все его элементы.

Ответ 2

Я считаю, что лучший способ обработки длинных выпадающих списков — разместить его в контейнере с фиксированной шириной div и использовать ширину: auto в теге select. Большинство браузеров будут содержать раскрывающийся список в div, но когда вы нажмете на него, он будет расширяться, чтобы отобразить полное значение параметра. Он не работает с IE Explorer, но есть исправление (как всегда, необходимо с IE). Ваш код будет выглядеть примерно так.

div.dropdown_container < width:10px; >select.my_dropdown < width:auto; >/*IE FIX */ select#my_dropdown < width:100%; >select:focus#my_dropdown

Ответ 3

  
// Shorten select option text if it stretches beyond max-width of select element $.each($('.shortenedSelect option'), function(key, optionElement) < var curText = $(optionElement).text(); $(this).attr('title', curText); // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system. var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3); if (curText.length >lengthToShortenTo) < $(this).text('. ' + curText.substring((curText.length - lengthToShortenTo), curText.length)); >>); // Show full name in tooltip after choosing an option $('.shortenedSelect').change(function() < $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title'))); >); 

Работает отлично. У меня была такая же проблема. Проверьте этот JSFiddle http://jsfiddle.net/jNWS6/426/

Ответ 4

  • Определить максимальную длину строки
  • Клип строка
  • (необязательно) добавить горизонтальный эллипс

Альтернативное решение: элемент выбора в вашем случае (только гадание) — элемент управления с одним выбором, и вместо этого вы можете использовать группу переключателей. Тогда вы могли бы лучше стилизовать стиль. Если у вас есть выбор [@multiple], вы можете сделать то же самое с группой флажков, потому что оба они могут рассматриваться как элемент управления с несколькими вариантами выбора.

Ответ 5

Ответ 6

u может просто использовать атрибут width для «style» для изменения длины раскрывающегося окна

Ответ 7

var i = 0; $("#container > option").each(function() < if($(this).val().length >i) < i = $(this).val().length; console.log(i); console.log($(this).val()); >>); 

Источник

Читайте также:  Переменные среды python ubuntu

Select width auto css

Last updated: May 17, 2023
Reading time · 4 min

banner

# Table of Contents

# How to set the Width of Select Options in HTML & CSS

Set the width CSS property of the select element and its option elements to set the width of a select dropdown using CSS.

If setting the property has no effect, you might have to use the !important flag.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> select width: 300px; > select option width: 300px; > style> head> body> h2>bobbyhadz.comh2> select name="languages" id="language-select"> option value="">--Choose an option--option> option value="javascript">JavaScriptoption> option value="typescript">TypeScriptoption> option value="python">Pythonoption> option value="java">Javaoption> option value="php">PHPoption> option value="php"> A very long select option abc 123 option> select> body> html>

Notice that we set the width of the select element and all of its option elements to the same value — 300px.

Copied!
select width: 300px; > select option width: 300px; >

If setting the width has no effect in your case, you might have to use the !important flag.

Copied!
select width: 300px !important; > select option width: 300px !important; >

The !important flag allows you to override styles that have higher precedence.

You will most likely want to set the width of the select and its option elements to the same value.

Here is an example of setting the width of the select element and its option elements to different values.

Copied!
select width: 150px; > select option width: 300px; >

Setting the width of the select element to a lower value than the width of the option elements is most likely not what you want.

When a wider option is selected, its value is truncated.

Here is an example that sets the width of the select element to 300px and the width of its option elements to 150px .

Copied!
select width: 300px; > select option width: 150px; >

# The width of your option elements might exceed the width of your select

In some cases, you might have very wide option elements.

very wide option elements

You can try to set the max-width CSS property on the select element but this likely won’t work.

Copied!
select width: 300px; max-width: 300px; >

Most browsers will still want to display the entire text of the option element, so setting the width CSS property might not have an effect.

In these cases, it’s best to use JavaScript to trim the text of the option element.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> body margin: 100px; > select width: 300px; > style> head> body> h2>bobbyhadz.comh2> select name="languages" id="language-select"> option value="">--Choose an option--option> option value="javascript">JavaScriptoption> option value="typescript">TypeScriptoption> option value="python">Pythonoption> option value="java">Javaoption> option value="php">PHPoption> option value="php"> bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com bobbyhadz.com option> select> script src="index.js"> script> body> html>

And here is the code for the index.js file.

Copied!
const optionElements = document.querySelectorAll('option'); Array.from(optionElements).forEach(element => if (element.textContent.length > 35) element.textContent = element.textContent.slice(0, 35) + '. '; > >);

We used the document.querySelectorAll method to select the option elements on the page.

We then converted the collection to an array using Array.from and used the Array.forEach to iterate over the array.

On each iteration, we check if the textContent of the current option element is greater than 35.

If the condition is met, we use the String.slice method to truncate the text to the first 35 characters and add an ellipsis . .

You might have to play around with the width of the select element and how many characters you want to display in your option elements depending on your use case.

# Set the Width of a Select Option in HTML & CSS using inline styles

If you weren’t able to set the width of the select element and its options using external styles, try using inline styles.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> select name="languages" id="language-select" style="width: 240px" > option style="width: 240px" value=""> --Choose an option-- option> option style="width: 240px" value="javascript"> JavaScript option> option style="width: 240px" value="typescript"> TypeScript option> option style="width: 240px" value="python">Pythonoption> option style="width: 240px" value="java">Javaoption> option style="width: 240px" value="php">PHPoption> option style="width: 240px" value="php"> A very long select option abc 123 option> select> body> html>

The example sets the width of the select element and its options using inline styles.

Copied!
select name="languages" id="language-select" style="width: 240px" > option style="width: 240px" value=""> --Choose an option-- option> select>

The width of both elements is set to 240px.

Inline styles have higher precedence than external stylesheets, so using this approach might work even if the previous approach didn’t work.

If none of the suggestions worked, you can try to use the !important flag which has the highest precedence.

Copied!
select width: 300px !important; > select option width: 300px !important; >

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Set the Value of a Select Element using JavaScript
  • Set a Radio button to Checked/Unchecked using JavaScript
  • Get the Value/Text of Select or Dropdown on Change using JS
  • Show a Div when a Select option is Selected using JavaScript
  • Show an Element if a Checkbox is checked using JavaScript
  • Show/Hide an element on Radio button Selection using JS
  • How to put an Input element on the same line as its Label
  • How to fetch and display JSON data in HTML using JavaScript
  • Remove the outline (border) around Inputs & Links in Chrome & Firefox
  • Change the Background Color on Scroll using JavaScript
  • How to set the width and height of a Span in CSS

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Установить ширину выпадающего элемента в вариантах выпадающего списка HTML

Я работаю над сайтом, который включает автоматическое заполнение окна выбора с помощью PHP script. Все это прекрасно работает, но проблема заключается в том, что то, что я использую для заполнения текстового поля, имеет очень длинные заголовки (это статьи журналов и заголовки презентаций). Выпадающий квадрат простирается до ширины самого длинного элемента, который простирается от края экрана, поэтому сделать полосу прокрутки невозможно. Я пробовал различные методы, пытаясь вручную установить раскрывающийся список с помощью CSS на определенную ширину, но до сих пор безрезультатно. Лучшее, что я сделал, чтобы установить поле «Выбор» на определенную ширину, но выпадающее меню само по себе намного шире.

Любые советы по этому поводу будут очень признательны.

Оказывается, что следующая строка CSS работает во всех основных браузерах, кроме Google Chrome (это то, что я тестировал в этой странице). Если решение для Chrome известно, об этом было бы полезно узнать.

ОТВЕТЫ

Ответ 1

Вы можете стилизовать (хотя и с некоторыми ограничениями) фактические элементы с помощью селектора option :

Таким образом вы не только сдерживаете раскрывающийся список, но и все его элементы.

Ответ 2

Я считаю, что лучший способ обработки длинных выпадающих списков — разместить его в контейнере с фиксированной шириной div и использовать ширину: auto в теге select. Большинство браузеров будут содержать раскрывающийся список в div, но когда вы нажмете на него, он будет расширяться, чтобы отобразить полное значение параметра. Он не работает с IE Explorer, но есть исправление (как всегда, необходимо с IE). Ваш код будет выглядеть примерно так.

div.dropdown_container < width:10px; >select.my_dropdown < width:auto; >/*IE FIX */ select#my_dropdown < width:100%; >select:focus#my_dropdown

Ответ 3

  
// Shorten select option text if it stretches beyond max-width of select element $.each($('.shortenedSelect option'), function(key, optionElement) < var curText = $(optionElement).text(); $(this).attr('title', curText); // Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system. var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3); if (curText.length >lengthToShortenTo) < $(this).text('. ' + curText.substring((curText.length - lengthToShortenTo), curText.length)); >>); // Show full name in tooltip after choosing an option $('.shortenedSelect').change(function() < $(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title'))); >); 

Работает отлично. У меня была такая же проблема. Проверьте этот JSFiddle http://jsfiddle.net/jNWS6/426/

Ответ 4

  • Определить максимальную длину строки
  • Клип строка
  • (необязательно) добавить горизонтальный эллипс

Альтернативное решение: элемент выбора в вашем случае (только гадание) — элемент управления с одним выбором, и вместо этого вы можете использовать группу переключателей. Тогда вы могли бы лучше стилизовать стиль. Если у вас есть выбор [@multiple], вы можете сделать то же самое с группой флажков, потому что оба они могут рассматриваться как элемент управления с несколькими вариантами выбора.

Ответ 5

Ответ 6

u может просто использовать атрибут width для «style» для изменения длины раскрывающегося окна

Ответ 7

var i = 0; $("#container > option").each(function() < if($(this).val().length >i) < i = $(this).val().length; console.log(i); console.log($(this).val()); >>); 

Источник

Оцените статью