CSS 表單主要是指通過 CSS 技術對 HTML 表單元素進行樣式化的過程。包含各種類型的輸入框,例如填充輸入框、帶邊框的輸入框、彩色的輸入框、獲得焦點的輸入框和有圖標的輸入框等等,甚至實現(xiàn)一些復雜的動畫效果。CSS 表單的應用非常廣泛,它可以用于任何需要用戶交互的網(wǎng)頁。
通過使用 CSS,可以極大地改善 HTML 表單的外觀:
First Name
Last Name
Country
一、輸入字段樣式
使用 width 屬性來確定輸入字段的寬度:
- First Name
實例:
input { width: 100%; }
上例適用于所有 <input> 元素。如果只想設置特定輸入類型的樣式,則可以使用屬性選擇器:
- input[type=text] :將僅選擇文本字段;
- input[type=password] :將僅選擇密碼字段;
- input[type=number] : 將僅選擇數(shù)字字段;
- 等等…
二、填充輸入框
使用 padding 屬性在文本字段內(nèi)添加空間。
提示:若有很多輸入,那么可能還需要添加外邊距,以便在它們之外添加更多空間:
- First Name
- Last Name
實例:
input[type=text] { width: 100%; padding: 12px 20px; margin: 8px 0; box-sizing: border-box; }
注意:box-sizing 屬性已經(jīng)設置為 border-box。這樣可以確保元素的總寬度和高度中包括內(nèi)邊距(填充)和最終的邊框。
三、帶邊框的輸入框
請使用 border 屬性更改邊框的粗細和顏色,并使用 border-radius 屬性添加圓角:
First Name
實例:
input[type=text] { border: 2px solid red; border-radius: 4px; }
如果僅需要下邊框,請使用 border-bottom 屬性:
First Name
實例:
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 屬性一起設置。還要注意,我們添加了一個較大的左內(nèi)邊距(padding-left)來留出圖標的空間:
實例:
input[type=text] { background-color: white; background-image: url('searchicon.png'); background-position: 10px 10px; background-repeat: no-repeat; padding-left: 40px; }
七、帶動畫效果的輸入框
在本例中,我們使用 CSS transition 屬性為搜索輸入框獲得焦點時的寬度變化設置動畫。
點擊后:
實例:
input[type=text] { transition: width 0.4s ease-in-out; } input[type=text]:focus { width: 100%; }
八、文本域樣式
使用 resize 屬性可防止對 textareas 調(diào)整大?。ń糜蚁陆堑摹白ト∑鳌保?/p>
實例:
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: #4CAF50; border: none; color: white; padding: 16px 32px; text-decoration: none; margin: 4px 2px; cursor: pointer; } /* 提示:請使用 width: 100%,以實現(xiàn)全寬按鈕 */
十、響應式菜單
請調(diào)整 TIY 編輯器窗口的大小來查看效果。當屏幕的寬度小于 600 像素時,使兩列上下堆疊而不是左右堆疊。