如果宽度设置为100%,我遇到的问题是textarea(可能还有任何输入元素)显示得太宽.这是我的CSS.
首先,我正在重置所有样式.
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
Run Code Online (Sandbox Code Playgroud)
然后将样式应用于我的表单.
form fieldset {
border: none;
border: 1px solid #ff0000;
padding: 5px;
}
form fieldset legend {
font-size: 20px;
font-weight: bold;
}
form textarea {
width: 100%;
height: 500px;
}
Run Code Online (Sandbox Code Playgroud)
最后是我的HTML.
<form method="post">
<fieldset>
<label for="area">Content</label>
<textarea id="area" name="area"></textarea>
</fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)
在Chrome和Firefox中(尚未测试其他版本),textarea在左侧正确填充5px,但在右侧textarea要么与字段集齐平,要么溢出一点.
有一件事是,如果我从页面中删除doctype,一切都会正确显示.
小智 8
虽然两个答案(目前)都提供有用的相关信息,但实际上都没有提供解决方案,这只是简单地添加box-sizing: border-box;到textarea,即
form textarea {
width: 100%;
box-sizing: border-box;
height: 500px;
}
Run Code Online (Sandbox Code Playgroud)
box-sizing: border-box;包括IE8(但不是IE7)在内的所有现代浏览器都支持,并且意味着在计算布局时使用包含边框和填充的元素宽度.
默认情况下通常content-box仅使用元素的内部宽度.大多数浏览器都提供自己的默认border和padding样式textarea,但并非总是box-sizing如此,结果可能是这width: 100%;意味着父的宽度加上浏览器的默认边框和填充,如果这些非零,则显然大于父级的宽度容器.