圖標文字對齊的幾種常見方法

引言

圖標文字對齊在平時的工做中是最多見的了,最先學習時候通常都是用vertical-align,可是因爲inline-block元素在和文字對齊時候的一些很麻煩的表現(見上一篇文章),你們應該都經歷過那種行框高度高出幾px的情形。簡單暴力的話還能夠用absolute定位方法。flex佈局出現之後不少時候用flex的居中對齊也是很方便的。web

實現

下面就以實現下面這個按鈕的樣式總結下幾種方法:佈局

圖片描述

.btn {
  display: inline-block;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  white-space: nowrap;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
}
.btn:hover, .btn:focus {
  color: #333;
  background-color: #e6e6e6;
  border-color: #8c8c8c;
}

<button class="btn"><i class="icon icon-info"></i> warning</button>

inline-block對齊法

思路很簡單,要讓圖標和文字對齊,就讓i元素高度和和文字行高一致而且是對齊,而後圖標背景居中就能夠了,問題在於inline-block元素內沒有內聯元素則其基線是margin底邊緣,這樣和文字對齊時候就會有上下交錯致使行框的高度都增高了,既然這樣咱們只要讓i元素基線和文字基線一致就能保證和文字對齊了,方案就是在其中包含文字同時文字又不顯示出來:學習

.icon {
  display: inline-block;
  width: 20px;
  height: 20px; //等於行高
  text-indent: -9999em; //隱藏文字
  white-space: nowrap;
}
.icon::before {
  content: 'icon';
}
.icon-info {
  background: url(./info-circle.png) no-repeat center;
}

用元素插入文字,用一個很大的text-indent來隱藏文字就能夠達到想要的效果了。flex

絕對定位法

說到絕對定位的方法你們確定都會了,給button元素設置relative,而後圖標絕對定位:url

.btn {
  ...
  position: relative;
  padding-left: 32px;
}

.icon {
  position: absolute;
  width: 20px;
  height: 20px;
  left: 12px;
}

若是上層元素沒有影響absolute的定位,其實能夠省去button的相對定位,直接使用無依賴絕對定位便可,用margin-left調整位置:spa

.btn {
  ...
  padding-left: 32px;
}
.icon {
  position: absolute;
  width: 20px;
  height: 20px;
  margin-left: -20px;
}

flex佈局法

這個直接給button設置display:inline-flex;align-items: center;便可。code

總結

關於使用哪種方法都是能夠選擇的,可是第一種方法但願你們能夠認真去思考下能收穫不少關於內聯元素對齊的知識。blog

相關文章
相關標籤/搜索