萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

輸入框內嵌圖標佈局實戰:CSS 定位實現用戶名/密碼圖標內嵌

登錄表單中常見需求:輸入框內嵌圖標(用戶圖標、鎖圖標),提升視覺辨識度。本文詳解絕對定位方案,兼容 IE6+ 所有瀏覽器。

HTML 結構

<div class="input-wrapper">
  <input type="text" id="username" class="input-field" placeholder="用戶名/郵箱">
  <div class="input-icon icon-user"></div>
</div>

<div class="input-wrapper">
  <input type="password" id="password" class="input-field" placeholder="密碼">
  <div class="input-icon icon-lock"></div>
</div>

CSS 核心樣式

.input-wrapper {
  position: relative;           /* 關鍵:建立定位上下文 */
  width: 307px;                 /* 容器寬度 */
  margin-bottom: 15px;
}

.input-field {
  width: 100%;
  height: 40px;
  padding: 0 45px 0 15px;       /* 右側預留圖標空間 */
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;       /* 關鍵:padding 不撐大寬度 */
  font-size: 14px;
}

.input-icon {
  position: absolute;           /* 絕對定位相對 .input-wrapper */
  top: 50%;                     /* 垂直居中 */
  right: 12px;                  /* 右側間距 */
  width: 16px;
  height: 16px;
  margin-top: -8px;             /* 修正垂直居中:高度一半 */
  z-index: 5;                   /* 確保在輸入框之上 */
  pointer-events: none;         /* 關鍵:點擊穿透到 input */
  background: no-repeat center center;
  background-size: contain;
}

.icon-user { background-image: url('/images/icon-user.svg'); }
.icon-lock { background-image: url('/images/icon-lock.svg'); }

/* 焦點狀態增強 */
.input-wrapper:focus-within .input-icon {
  opacity: 0.8;
}
.input-field:focus {
  border-color: #0066cc;
  outline: none;
  box-shadow: 0 0 0 3px rgba(0,102,204,0.2);
}

關鍵技術點解析

技術點 作用 關鍵代碼
父容器 relative 建立定位參考系 .input-wrapper { position: relative; }
圖標 absolute 脫離文檔流精準定位 .input-icon { position: absolute; }
垂直居中 top:50% + margin-top:-半高 top: 50%; margin-top: -8px;
輸入框右側 padding 避免文字遮擋圖標 padding-right: 45px;
pointer-events: none 點擊穿透聚焦輸入框 .input-icon { pointer-events: none; }
box-sizing: border-box 寬度包含 padding/border *:before, *:after { box-sizing: border-box; }

IE6/7 兼容補丁

* html .input-wrapper { zoom: 1; }        /* IE6 觸發 hasLayout */
* html .input-icon { top: 12px; }         /* IE6 無 margin-top 負值居中 */
*+html .input-icon { top: 12px; }         /* IE7 修正 */

現代增強:CSS 原生表單驗證樣式

.input-field:valid:not(:placeholder-shown) + .icon-user {
  background-image: url('/images/icon-check.svg');  /* 綠色勾號 */
}
.input-field:invalid:not(:placeholder-shown) + .icon-lock {
  background-image: url('/images/icon-error.svg');  /* 紅色叉號 */
}

替代方案對比

方案 優點 缺點 適用場景
背景圖片 + padding 無額外 DOM、最簡潔 無法動態切換圖標、無法點擊圖標觸發事件 靜態裝飾性圖標
絕對定位圖標元素 可動態切換、可綁定事件、語義清晰 需額外 DOM、定位代碼較多 需交互的圖標(密碼顯示/隱藏、清空輸入)
CSS :has() 父選擇器 無需 wrapper、純 CSS 狀態響應 瀏覽器支援較新(2023+) 現代項目、漸進增強
copyright © 萬盛學電腦網 all rights reserved