萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

第九天:CSS 表單設計——輸入框美化、按鈕圖標化、下拉框樣式與 Label 可用性

表單是用戶交互核心。本章系統講解文本框/域美化、圖片按鈕製作、難搞的下拉框樣式突破、Label 標簽提升可用性,打造專業級表單體驗。

一、文本框與文本域深度美化

1. 文本框四大進階樣式

Class效果描述關鍵屬性
.text1橙邊藍字border:1px solid #f60; color:#03C;
.text2綠邊加粗大字、固定高寬border:2px solid #390; width:200px; height:24px; font:bold 16px/1.6
.text3粉邊右側圖標background:url(icon9.gif) no-repeat right 3px
.text4橙邊 GIF 動畫背景background:url(bg_9.gif) no-repeat

四種文本框樣式效果

2. 文本域關鍵屬性

.area {
    border: 1px solid #F90;
    overflow: auto;       /* 內容未超高時隱藏滾動條 */
    background: #fff url(bg_9_1.gif) no-repeat right bottom;
    width: 99%; height: 100px;
}

文本域樣式對比

二、圖片美化提交按鈕

<input type="submit"> 樣式重置要點:

  • border: none 去除系統邊框
  • cursor: pointer 手型游標
  • text-indent: -999em 隱藏文字(配合背景圖),保留語義
  • 寬度固定用單圖,自適應用滑動門(兩張圖左/右)

五種按鈕樣式對比

.btn02 { /* 固定寬度,橫向平鋪 */ background:#fff url(btn_bg2.gif) 0 0; width:55px; height:22px; border:1px solid #90be4a; }
.btn04 { /* 固定寬度,圖片不同區域 */ background:url(btn_bg2.gif) 0 -24px; width:70px; height:22px; border:1px solid #dbb119; }
.btn07 { /* 自適應寬度,左圖片 */ background:url(submit_bg.gif) 0 -8px; border:1px solid #cfab25; height:32px; padding-top:2px; }
.btn08 { /* 自適應寬度,右圖片 */ background:url(submit_bg.gif) 0 -64px; border:1px solid #8b9c56; height:32px; padding-top:2px; }
.btn09 { /* 完全圖片按鈕,固定尺寸 */ background:url(btn_bg.gif) no-repeat; width:107px; height:37px; border:none; }

五種按鈕效果對比

三、下拉列表樣式突破方案

<select> 為替換元素,瀏覽器渲染受系統控制,CSS 控制力極弱(僅能改字體、邊框、寬高、背景色)。

主流解決方案對比

推薦:appearance:none 方案代碼

select {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background: #fff url(arrow-down.svg) no-repeat right 0.5rem center / 1.2em;
    padding-right: 2.5rem; /* 騰出箭頭空間 */
    border: 1px solid #ccc; border-radius: 4px;
}
select::-ms-expand { display: none; } /* IE10/11 隱藏箭頭 */

四、Label 標簽提升可用性與無障礙

<label> 關聯表單控件,點擊文字即聚焦控件,對屏幕閱讀器至關重要。

兩種關聯方式

<!-- 1. 隱式關聯:包裹控件 -->
<label>用戶名:<input type="text" name="username" /></label>

<!-- 2. 顯式關聯:for + id(推薦,結構靈活) -->
<label for="username">用戶名:</label>
<input type="text" id="username" name="username" />

進階:單選/複選框美化(隱藏原生,用 Label 做樣式)

.radio-group input { position: absolute; opacity: 0; }
.radio-group label {
    display: inline-block; padding-left: 24px;
    background: url(radio.png) no-repeat 0 0; cursor: pointer;
}
.radio-group input:checked + label { background-position: 0 -24px; }

標準之路提示:表單設計核心原則——「語義優先,漸進增強」。優先保證 HTML 結構正確、Label 關聯完整、鍵盤可操作,再疊加視覺樣式。現代項目建議引入成熟表單庫(React Hook Form + Yup / VeeValidate)統一狀態管理與驗證。

copyright © 萬盛學電腦網 all rights reserved
方案原理優點缺點
原生 appearance:none + 背景箭頭隱藏原生箭頭,用背景圖模擬零 JS、輕量、語義保留跨瀏覽器箭頭位置難對齊、下拉面板樣式不可控
JS 模擬(Select2, Choices.js, Tom Select)隱藏原生,構建 ul/li 模擬下拉完全可控、搜索、分組、多選、遠程數據體積大、需維護同步、無障礙需額外處理
CSS-only 自定義下拉面板:focus-within + 絕對定位 ul輕量、無 JS、可動畫鍵盤導航複雜、移動端體驗一般