Html 在 css 级别和元素级别定义的输入宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6969810/
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 09:55:50  来源:igfitidea点击:

Input width defined at css level and at the element level

htmlcss

提问by DevSharp

<style>

input[type="text"] 
{
    width: 200px;
    border: 1px solid #CCC;
}

</style>
<body>

<input type="text" name="test" value="test" size="5" />
</body>

When this is viewed on browser (Firefox 5), the "size" it appears is a fixed 200px. It seems the size I specified is completely ignored.

当在浏览器 (Firefox 5) 上查看时,它出现的“大小”是固定的 200 像素。似乎我指定的大小被完全忽略了。

This is from a MVC project, and that is the default style css that comes with it. For the time being, I took off the width: 200px. But is there a way to keep it there, and override it at the "input" level?

这是来自 MVC 项目,这是它附带的默认样式 css。暂时我去掉了宽度:200px。但是有没有办法将它保留在那里,并在“输入”级别覆盖它?

I also tried

我也试过

<input type="text" name="test" value="test" width="50px" />

It did not override at all.

它根本没有覆盖。

回答by Evan

If you want to override the CSS width at the element level, try applying the style tag to the element directly:

如果要在元素级别覆盖 CSS 宽度,请尝试将样式标签直接应用于元素:

<input type="text" name="test" value="test" style="width: 50px;" />

This works for me:

这对我有用:

<html>
   <style>

      input[type="text"] 
      {
         width: 200px;
         border: 1px solid #CCC;
      }
</style>
<body>
      <input type="text" name="test" value="test" style="width: 50px;" />
</body>
</html>

Edited to Add:

编辑添加:

Yes, mixing HTML w/CSS is considered a no-no, so the propersolution would be to extract it out to a class in the end:

是的,混合 HTML 和 CSS 被认为是禁忌,所以正确的解决方案是最后将其提取到一个类中:

.my_text_box {
    width: 50px;
 }

Then:

然后:

<input type="text" name="test" value="test" class="my_text_box" />

回答by Brock Adams

Don't set display stylein the HTML.

不要在 HTML 中设置显示样式

Use:

用:

<input class="narrowInput" type="text" name="test" value="test" />

Or:

或者:

<input id="narrowInput" type="text" name="test" value="test" />

Only don't use "narrowInput". Use a name that has a business meaning, that is: one that describes the purpose of the input data.

只是不要使用“narrowInput”。使用具有业务意义的名称,即:描述输入数据用途的名称。

Then the CSS is:

那么CSS是:

input.narrowInput
{
    width: 50px;
}

Or:

或者:

#narrowInput
{
    width: 50px;
}

回答by Jason Gennaro

Remove either

删除任一

input[type="text"] 
{
    width: 200px; //THIS
}

or

或者

<input type="text" name="test" value="test" size="5" <--//THIS />

<input type="text" name="test" value="test" size="5" <--//THIS />

Choose to style using one or the other.

选择使用其中一个来设计样式。