Html CSS 包含输入文本到 100% 宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8951558/
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
CSS Contain input text to 100% width
提问by w.donahue
So when I set the input like this example the text box, because it has a border and padding by default, will be wider than 200px.
所以当我像这个例子一样设置输入时,文本框,因为它默认有边框和填充,将比 200px 宽。
<div style="width:200px; background-color:red;">
<input type="text" name="fname" style="width:100%;"/>
</div>
I know I can force the text box to fit within the 200px by setting a class to the input tag and tagging it with this CSS
我知道我可以通过为 input 标签设置一个类并用这个 CSS 标记它来强制文本框适合 200px
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
Is there a better way to get this text box to size correctly, i.e. to fill 100% as I want it to do? I cannot use fixed sizes. I am using CSS themes so the text box padding, margins, etc are not known at compile time. They can be changed out by the user on the fly. So the solution must work regardless of what the text box's padding, border, and margin is.
有没有更好的方法可以让这个文本框正确调整大小,即按照我想要的方式填充 100%?我不能使用固定尺寸。我正在使用 CSS 主题,因此在编译时不知道文本框的填充、边距等。用户可以随时更改它们。因此,无论文本框的填充、边框和边距是什么,解决方案都必须有效。
回答by mrtsherman
I think you have already answered your own question. box-sizing: border-box;
is really the only CSS means of getting the element to fit inside its parent. css-tricks goes into great detail about this here.
我想你已经回答了你自己的问题。box-sizing: border-box;
确实是使元素适合其父元素的唯一 CSS 方法。css-tricks 在这里详细介绍了这一点。
http://css-tricks.com/box-sizing/
http://css-tricks.com/box-sizing/
I am unaware of any other CSS you could use other than using javascript to perform some calculations and then modifying your input elements.
除了使用 javascript 执行一些计算然后修改输入元素之外,我不知道您可以使用任何其他 CSS。
回答by Vladimir Starkov
Yes.You can doit.
是的。你可以做到。
You can do it without using box-sizing
and not clearsolutions like width~=99%
.
Demo on jsFiddle:
你能做到不使用box-sizing
和不清晰的像的解决方案width~=99%
。
jsFiddle 上的演示:
HTML markup:
HTML 标记:
<div class="input_wrap">
<input type="text" />
</div>
CSS:
CSS:
div {
padding: 6px 17px; /* equal to negative input's margin for mimic normal `div` box-sizing */
}
input {
width: 100%; /* force to expand to container's width */
border: 7px solid #DFDFDF;
padding: 0 10px;
margin: 0 -17px; /* negative margin = border-width + horizontal padding */
}
回答by Eric Yin
<div style="width:200px; background-color:red;">
<input type="text" name="fname" style="width:100%;border:1px;padding:4px;margin:-5px"/>
</div>