Html 如何控制select标签的宽度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10671614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:32:42  来源:igfitidea点击:

How to control the width of select tag?

htmlcss

提问by Question Overflow

I have a list of countries, some with a very long name:

我有一个国家/地区列表,其中一些国家/地区的名称很长:

<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>?land Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>

By default, the select box would be as long as the longest option in the list. I want to create a select box such that it exhibits the default behaviour when viewed from a wide browser window, but fit in nicely to 90% of container width when viewed from a narrow browser window, smaller than the length of the longest option.

默认情况下,选择框与列表中最长的选项一样长。我想创建一个选择框,使其在从宽浏览器窗口查看时表现出默认行为,但在从窄浏览器窗口查看时非常适合容器宽度的 90%,小于最长选项的长度。

I tried min-width: 90%;, but it didn't work. Can this be done by CSS styling alone?

我试过了min-width: 90%;,但没有用。这可以仅通过 CSS 样式来完成吗?

回答by Krishanu Dey

USE style="max-width:90%;"

style="max-width:90%;"

<select name=countries  style="max-width:90%;">
 <option value=af>Afghanistan</option>
 <option value=ax>?land Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>  

LIVE DEMO

现场演示

回答by animuson

You've simply got it backwards. Specifying a minimum width would make the select menu always be at leastthat width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.

你只是把它倒退了。指定最小宽度将使选择菜单始终至少为该宽度,因此无论窗口大小如何,它都会继续扩展到 90%,也至少是其最长选项的大小。

You need to use max-widthinstead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.

你需要max-width改用。这样,它将让选择菜单扩展到其最长的选项,但如果扩展超过您设置的最大 90% 宽度,则将其缩小到该宽度。

回答by Rahi.Shah

Add div wrapper

添加 div 包装器

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>?land Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

然后写CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

希望这会有所帮助。