如何使用 CSS 建立響應式內聯表單?
響應式內聯表單是指所有元素都為內聯元素,且與特定標籤左對齊的表單。為了顯示響應性,即當網頁瀏覽器大小調整時,我們將內聯表單設定為將所有輸入欄位堆疊在彼此之上。此概念適用於較小的螢幕。讓我們看看如何使用 CSS 建立響應式內聯表單。
建立表單
要建立表單,請使用<form>元素。我們在表單中設定了兩個輸入欄位和一個按鈕 -
<form> <label for="email">Email:</label> <input type="email" id="email" placeholder="Enter email" name="email" /> <label for="pass">Password:</label> <input type="password" id="pass" placeholder="Enter password" name="pass"/> <button type="submit">Submit</button> </form>
設定表單樣式
我們使用 display 屬性將表單定位為 flex。flex-row 簡寫設定為 row wrap,即flex-direction 為 row,flex-wrap 為 wrap。所有專案的對齊方式使用align-items 屬性居中 -
form { display: flex; flex-flow: row wrap; align-items: center; }
提交按鈕
表單的提交按鈕樣式如下。將游標屬性設定為 pointer 以使其看起來可點選 -
form button { padding: 10px 20px; font-size: 20px; background-color: rgb(39, 22, 141); border: 1px solid #ddd; color: white; cursor: pointer; font-weight: bolder; border-radius: 4px; }
設定響應性
媒體查詢用於設定響應性。當螢幕尺寸小於 800px 時,輸入欄位將堆疊在彼此之上。我們使用flex-direction 屬性和值column實現了這一點 -
@media (max-width: 800px) { form input { margin: 10px 0; } form { flex-direction: column; align-items: stretch; } }
示例
以下是使用 CSS 建立響應式內聯表單的程式碼 -
<!DOCTYPE html> <html> <head> <style> body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } form { display: flex; flex-flow: row wrap; align-items: center; } form label { margin: 5px 10px 5px 0; } form input { margin: 5px 10px 5px 0; padding: 10px; } form button { padding: 10px 20px; font-size: 20px; background-color: rgb(39, 22, 141); border: 1px solid #ddd; color: white; cursor: pointer; font-weight: bolder; border-radius: 4px; } form button:hover { background-color: rgb(113, 65, 225); } @media (max-width: 800px) { form input { margin: 10px 0; } form { flex-direction: column; align-items: stretch; } } </style> </head> <body> <h1>Responsive Inline Form Example</h1> <form> <label for="email">Email:</label> <input type="email" id="email" placeholder="Enter email" name="email" /> <label for="pass">Password:</label> <input type="password" id="pass" placeholder="Enter password" name="pass"/> <button type="submit">Submit</button> </form> </body> </html>
廣告