當須要開發如上這樣一個搜索框時。html
由於是移動端開發,手機屏幕寬度的不肯定性,因此不能使用平時的定寬開發。web
分析如上圖:app
1.該搜索框由兩部分組成:input搜索框+取消按鈕;
webapp
2.搜索框距離左右兩邊的距離是固定的,即圖中1和2相等;佈局
3.取消按鈕的大小是固定的,以及距離input距離是固定的;
優化
4.input隨着屏幕寬度的變化自適應變化。
url
代碼:spa
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>搜索框 - div中input自適應</title> <style> *{ margin:0; padding:0; } .search{ position: relative; height: 32px; border-bottom:1px solid #d3d3d3; overflow:hidden; background: #fff; text-align: center; overflow:hidden; padding:4px 20px; } .search_bar{ height: 32px; margin-right:92px; } .search_bar>input{ width:100%; display:inline-block; *display:inline; border:1px solid #ccc; border-radius:5px; font-size:14px; height:30px; padding:0 10px 0 32px; background: #f0f0f0 url(/images/webapp/icon.png) no-repeat; background-size:32px 32px; } .search_btn>span{ position:absolute; top:4px; right:20px; z-index:9; line-height:32px; color:green; } </style> </head> <body> <!--設置總體佈局--> <div> <!--input包裹層,利用塊元素的特性(width:100%)使其能夠徹底填充父級div,使用margin-right在右邊留出固定寬度--> <div> <!--使input完整填充input包裹層,同時設置其padding值,用以存放搜索小圖標+頁面優化--> <input type="text" placeholder="搜索"/> </div> <!--btn包裹層,無關緊要,使用position將其放置在input右邊固定位置,利用z-index使得圖層不會被覆蓋--> <div> <span>取消</span> </div> </div> </body> </html>