原生 <select> 樣式受系統控制極難美化。利用容器 clip 裁剪隱藏原生邊框,露出自定義邊框的容器。
<style>
.select-wrapper {
display: inline-block;
border: 1px solid #00ff00; /* 自定義邊框 */
width: 180px;
height: 17px;
/* 裁剪區域:top right bottom left */
/* 隱藏 select 自帶邊框(約 2px),只露出內部文字區域 */
clip: rect(0px, 179px, 16px, 0px);
overflow: hidden;
vertical-align: middle;
}
.select-wrapper select {
position: relative;
left: -2px; /* 抵消左邊框 */
top: -2px; /* 抵消上邊框 */
width: 183px; /* 比容器寬 3px,確保右側箭頭可見 */
height: 17px;
line-height: 14px;
border: 0; *關鍵:移除原生邊框*
font-size: 12px;
color: #909993;
background: transparent; /* 透明背景 */
-webkit-appearance: none; /* 移除系統默認樣式(部分瀏覽器) */
-moz-appearance: none;
appearance: none;
}
</style>
<div class="select-wrapper">
<select id="idselect1" onchange="select1();" hidefocus>
<option selected>網頁陶吧</option>
<option>設計在線</option>
<option>辦公軟件</option>
<option>工具軟件</option>
</select>
</div>
| 屬性 | 值 | 作用 |
|---|---|---|
容器 clip | rect(0, 179px, 16px, 0) | 只顯示 select 內部 16px 高、179px 寬的區域,裁掉原生邊框 |
select left/top: -2px | 負偏移 | 將 select 內容區對齊容器可視區 |
select width: 183px | 容器寬 + 3px | 確保右側下拉箭頭不被裁剪 |
select border:0 | 無邊框 | 核心:移除系統默認邊框 |
appearance:none | 移除原生外觀 | 現代瀏覽器進一步重置樣式 |
/* 現代方案:隱藏原生箭頭,用偽元素畫自定義箭頭 */
.custom-select {
position: relative;
display: inline-block;
border: 1px solid #ddd;
border-radius: 4px;
background: #fff;
font-size: 14px;
min-width: 180px;
}
.custom-select select {
appearance: none; /* 關鍵:移除原生箭頭 */
-webkit-appearance: none;
-moz-appearance: none;
padding: 8px 36px 8px 12px; /* 右側留空給自定義箭頭 */
border: none;
background: transparent;
width: 100%;
font: inherit;
color: inherit;
cursor: pointer;
z-index: 1; /* 置於偽元素上層可點擊 */
}
.custom-select::after {
content: '';
position: absolute;
right: 12px; top: 50%;
transform: translateY(-50%);
width: 0; height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 6px solid #666; /* 三角形箭頭 */
pointer-events: none; *關鍵:點擊穿透到 select*
}
.custom-select:hover { border-color: #aaa; }
.custom-select:focus-within { border-color: #3498db; box-shadow: 0 0 0 2px rgba(52,152,219,.2); }
<div class="custom-select">
<select id="idselect1" onchange="select1();">
<option selected>網頁陶吧</option>
<option>設計在線</option>
<option>辦公軟件</option>
<option>工具軟件</option>
</select>
</div>
clip 裁剪是 IE6-8 時代的 hack 方案,現代瀏覽器**強烈建議使用 appearance: none + 偽元素** 方案:代碼更簡潔、無魔法數字、響應式友好、無需固定寬高、支持圓角陰影等現代樣式。若必須兼容 IE9-,可結合條件註釋引入 clip 方案作為降級。