CSS讓搜索框居中,其實(shí)是一個相對簡單的問題,在CSS中,我們可以使用多種方法來實(shí)現(xiàn)搜索框的居中顯示,下面,我將介紹一種常用的方法——使用flexbox布局。
我們需要創(chuàng)建一個包含搜索框的HTML結(jié)構(gòu),假設(shè)我們的HTML代碼如下:
<div class="search-container"> <input type="text" class="search-input" placeholder="請輸入搜索關(guān)鍵詞"> <button class="search-button">搜索</button> </div>
我們可以在CSS中設(shè)置.search-container
為flexbox布局,并將.search-input
和.search-button
設(shè)置為flex子項,我們可以使用justify-content
屬性將子項居中顯示,示例代碼如下:
.search-container { display: flex; justify-content: center; align-items: center; } .search-input { width: 200px; height: 30px; border: 1px solid #000; border-radius: 5px; padding: 5px; } .search-button { height: 30px; border: 1px solid #000; border-radius: 5px; background-color: #007bff; color: #fff; }
在上面的代碼中,我們將.search-container
的高度設(shè)置為0,這樣可以讓搜索框在垂直方向上居中顯示,我們還設(shè)置了.search-input
和.search-button
的樣式,包括寬度、高度、邊框、邊框半徑等屬性。
我們可以在HTML頁面中引入上述CSS代碼,即可實(shí)現(xiàn)搜索框的居中顯示,示例代碼如下:
<!DOCTYPE html> <html> <head> <title>搜索框居中顯示</title> <style> .search-container { display: flex; justify-content: center; align-items: center; } .search-input { width: 200px; height: 30px; border: 1px solid #000; border-radius: 5px; padding: 5px; } .search-button { height: 30px; border: 1px solid #000; border-radius: 5px; background-color: #007bff; color: #fff; } </style> </head> <body> <div class="search-container"> <input type="text" class="search-input" placeholder="請輸入搜索關(guān)鍵詞"> <button class="search-button">搜索</button> </div> </body> </html>
在上面的代碼中,我們將CSS代碼直接寫在了HTML頁面的<style>
標(biāo)簽中,我們也可以選擇將CSS代碼寫在一個單獨(dú)的CSS文件中,并通過<link>
標(biāo)簽引入HTML頁面,無論哪種方式,都可以實(shí)現(xiàn)搜索框的居中顯示。