Skip to content

CSS 表单

用 CSS 可以为输入框按钮标签单选/复选框等表单元素设置边框、内边距、焦点样式、禁用样式等,让表单更统一、易用。

常用表单元素与选择器

  • input:文本、密码、提交等
  • textarea:多行文本
  • button / input[type="submit"]:按钮
  • label:标签
  • fieldset / legend:分组与标题
  • :focus:获得焦点时
  • :disabled:禁用时
  • :placeholder:占位符文字(需加前缀)

输入框与文本框

css
input[type="text"],
input[type="email"],
input[type="password"],
textarea {
  width: 100%;
  max-width: 400px;
  padding: 10px 12px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

input:focus,
textarea:focus {
  border-color: #0066cc;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.2);
}

input:disabled,
textarea:disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

占位符样式

css
input::placeholder,
textarea::placeholder {
  color: #999;
}

按钮

css
button,
input[type="submit"],
input[type="button"] {
  padding: 10px 20px;
  font-size: 16px;
  border: none;
  border-radius: 4px;
  background: #0066cc;
  color: white;
  cursor: pointer;
}

button:hover,
input[type="submit"]:hover {
  background: #0052a3;
}

button:focus,
input[type="submit"]:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 102, 204, 0.5);
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

标签与布局

css
label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
}

.form-group {
  margin-bottom: 16px;
}

单选与复选框

不同浏览器对原生单选/复选框的样式支持不一,常用 appearance: none 去掉默认样式后自己画,或使用 accent-color(现代浏览器)统一强调色:

css
input[type="radio"],
input[type="checkbox"] {
  width: 18px;
  height: 18px;
  accent-color: #0066cc;
}

小结

  • input / textarea / button 等选择器设边框、内边距、圆角。
  • :focus 设焦点样式;:disabled 设禁用样式;::placeholder 设占位符样式。
  • 按钮用 paddingbackground:hover:focus 统一风格。
  • accent-color 可快速统一单选/复选框颜色。

下一节学习 CSS 计数器