CSS 表单
使用 CSS 可以大大改善 HTML 表单的外观:
设置输入字段的样式
使用 width 属性确定输入字段的宽度:
示例
input {
width: 100%;
}
上述示例适用于所有 <input>
元素。如果您只想设置特定输入类型的样式,则可以使用属性选择器:
input[type=text] - 仅选择文本字段
input[type=password] - 仅选择密码字段
input[type=number] - 仅选择数字字段
等等。
padding 填充输入
使用 padding 属性在文本字段内添加空间。
提示:当您有许多输入内容接连出现时,您可能还需要添加一些边距,以便在输入内容外部添加更多空间:
示例
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
box-sizing: border-box;
}
请注意,我们已将 box-sizing 属性设置为 border-box。这可确保元素的总宽度和高度中包含填充和最终边框。
带边框border 的输入
使用 border 属性更改边框大小和颜色,并使用 border-radius 属性添加圆角:
示例
input[type=text] {
border: 2px solid red;
border-radius: 4px;
}
如果您只想要底部边框,请使用 border-bottom 属性:
示例
input[type=text] {
border: none;
border-bottom: 2px solid red;
}
彩色输入
使用 background-color 属性为输入添加背景颜色,使用 color 属性更改文本颜色:
示例
input[type=text] {
background-color: #3CBC8D;
color: white;
}
聚焦输入
默认情况下,某些浏览器会在输入获得焦点(单击)时在其周围添加蓝色轮廓。您可以通过向输入添加 outline: none; 来删除此行为。
使用 :focus 选择器在输入字段获得焦点时对其进行处理:
示例
input[type=text]:focus {
background-color: lightblue;
}
示例
input[type=text]:focus {
border: 3px solid #555;
}
带有图标/图像的输入
如果您希望在输入内放置图标,请使用 background-image 属性并使用 background-position 属性对其进行定位。另请注意,我们添加了一个较大的左填充以保留图标的空间:
示例
input[type=text] {
background-color: white;
background-image: url('searchicon.png');
background-position: 10px 10px;
background-repeat: no-repeat;
padding-left: 40px;
}
动画搜索输入
在此示例中,我们使用 CSS transition 属性在获得焦点时为搜索输入的宽度设置动画。您将在后面的 CSS Transitions 章节中了解有关 transition 属性的更多信息。
示例
input[type=text] {
transition: width 0.4s ease-in-out;
}
input[type=text]:focus {
width: 100%;
}
设置文本区域样式
提示:使用 resize 属性可防止调整文本区域的大小(禁用右下角的“抓取器”):
示例
textarea {
width: 100%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}
设置选择菜单样式
示例
select {
width: 100%;
padding: 16px 20px;
border: none;
border-radius: 4px;
background-color: #f1f1f1;
}
设置输入按钮的样式
示例
input[type=button], input[type=submit], input[type=reset] {
background-color: #04AA6D;
border: none;
color: white;
padding: 16px 32px;
text-decoration: none;
margin: 4px 2px;
cursor: pointer;
}
/* 提示:全宽按钮使用 width: 100% */
总结
本文介绍了CSS设置表单样式,如有问题欢迎私信和评论