搜尋框看起來簡單,卻很吃細節:寬高精度要先算好,輸入框與按鈕的對齊、內距、邊框視覺都要一起考慮,否則字會貼著邊框、按鈕會歪掉一兩像素。

一個搜尋框基本上只有三塊:左邊的輸入框、右邊的按鈕,以及包住兩者的外層容器。
<div class="center_child1">
<form>
<input type="text" name="search" placeholder="search 練習">
<button>搜尋</button>
<!-- 京東用的是 button 標籤;百度則是 <input type="submit"> -->
</form>
</div>
.center_child1 {
width: 538px;
height: 36px;
overflow: hidden; /* 讓浮動子元素被包住,外框才撐得開 */
border: 2px solid #BD1D17;
}
.center_child1 input {
width: 456px;
height: 24px;
float: left;
padding: 6px 2px; /* 內距撐開高度,文字才不貼邊 */
background-color: transparent;
border: none; /* 拿掉 input 自帶的邊框 */
outline: none;
font-size: 16px;
}
.center_child1 button {
width: 76px;
height: 36px;
float: right;
background: #BD1D17;
border: none;
color: #fff;
font-size: 15px;
}
1. 先定外框。外框 538px 寬、含 2px 邊框,所以內容可用寬度是 534px。按鈕佔 76px,剩給輸入框 458px;扣掉左右各 2px 的 padding,width 設 456px 剛好對齊。這組數字必須一起算,改任何一項都要同步調整其他兩項。
2. 左右浮動 + overflow。輸入框 float: left、按鈕 float: right,外層一定要 overflow: hidden(或改用 flex)來清除浮動,否則外框高度會塌成 0。
3. 用 padding 撐高度。input 的 height 設 24px、上下 padding 各 6px,加上 2px 邊框剛好 36px,與按鈕同高,視覺才會齊平。這也是為什麼不要直接把 height 設 36px——文字會貼死在正中而顯得擁擠。
浮動寫法每改一次尺寸就要重算三個數字,維護成本很高。改用 flex 後,寬度會自動分配:
.search {
display: flex;
width: 538px;
height: 36px;
border: 2px solid #BD1D17;
box-sizing: border-box;
}
.search input {
flex: 1; /* 自動吃掉剩下的空間 */
min-width: 0; /* 避免內容過長時撐破容器 */
padding: 0 8px;
border: none;
outline: none;
font-size: 16px;
}
.search button {
width: 76px;
border: none;
background: #BD1D17;
color: #fff;
cursor: pointer;
}
.search button:hover { background: #a3160f; }
搭配 <div class="search"><input type="search"><button type="submit">搜尋</button></div> 使用。幾個小細節值得一併處理:input 用 type="search" 手機才會出現「搜尋」鍵;加 aria-label 讓螢幕閱讀器知道這個欄位的用途;:focus-within 可以讓整框在聚焦時改變邊框顏色,回饋更清楚。
.search:focus-within { border-color: #333; }
最後記得包在 form 裡並設定 action,讓沒有 JS 也能靠 Enter 送出——這是搜尋框最容易被忽略、卻最不該缺的功能。