<input type="checkbox"> 與後方文字並排時,不同瀏覽器垂直對齊基線差異導致 1-3px 像素級錯位,特別是 IE6 表現最為明顯。本文提供徹底解決方案。
<div class="checkbox-group">
<input type="checkbox" id="agree" name="agree">
<label for="agree">我已閱讀並同意《用戶協議》</label>
</div>
現象:Chrome/Firefox 基線對齊,IE6/7 復選框偏高或偏低,視覺不對齊。
.checkbox-group {
position: relative; /* 建立定位上下文 */
display: inline-flex; /* 現代:Flex 內建對齊 */
align-items: center; /* 垂直居中對齊 */
gap: 8px; /* 間距控制 */
}
/* 傳統瀏覽器兼容方案 */
.checkbox-group input[type="checkbox"] {
position: relative; /* 關鍵:啟用相對定位微調 */
top: 2px; /* 視覺微調:根據字體大小調整 1-3px */
vertical-align: middle; /* 基線對齊輔助 */
margin: 0; /* 重置默認外邊距 */
}
<style>
.checkbox-wrapper {
display: inline-block;
*display: inline; /* IE6/7 inline-block hack */
zoom: 1; /* 觸發 hasLayout */
vertical-align: middle;
}
.checkbox-wrapper input[type="checkbox"] {
position: relative;
top: 1px; /* 經驗值:1-2px 視字體而定 */
*top: 2px; /* IE6/7 專用微調 */
vertical-align: middle;
margin: 0 6px 0 0;
}
.checkbox-wrapper label {
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
cursor: pointer;
line-height: 1.4; /* 確保行高穩定 */
}
</style>
<span class="checkbox-wrapper">
<input type="checkbox" id="agree" name="agree">
<label for="agree">我已閱讀並同意《用戶協議》</label>
</span>
.checkbox-modern {
display: inline-flex;
align-items: center; /* 垂直居中:解決所有對齊問題 */
gap: 8px; /* 間距 */
font-size: 14px;
line-height: 1.5;
cursor: pointer;
}
.checkbox-modern input[type="checkbox"] {
flex-shrink: 0; /* 防止壓縮 */
width: 16px;
height: 16px;
accent-color: #0066cc; /* 現代:自定義復選框顏色 */
}
.custom-checkbox {
position: relative;
display: inline-flex;
align-items: center;
gap: 8px;
cursor: pointer;
font-size: 14px;
}
.custom-checkbox input {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
.custom-checkbox .checkmark {
width: 18px;
height: 18px;
border: 2px solid #ccc;
border-radius: 3px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s;
flex-shrink: 0;
}
.custom-checkbox input:checked + .checkmark {
background: #0066cc;
border-color: #0066cc;
}
.custom-checkbox input:checked + .checkmark::after {
content: "";
width: 5px;
height: 10px;
border: solid white;
border-width: 0 2px 2px 0;
transform: rotate(45deg) translateY(-1px);
}
line-height 不一致vertical-align: baseline 默認值,inline 元素基線對齊input 是替換元素,基線為底邊,與文字基線不一致label for= 關聯,點擊文字也能切換line-height 或使用 Flex align-items: centerwidth/height,避免瀏覽器默認尺寸差異vertical-align: middle 作為基線對齊輔助*display: inline; zoom: 1 觸發 inline-block 行為accent-color 或自定義重構