用CSS畫簡單圖標

用CSS畫了三個圖標,叉號,排行符號,搜索符號。先上效果圖啦啦啦。
spa

附上CodePen連接,點我點我code

思路

用叉號舉例哈。叉號能夠看做兩個互相垂直的矩形框。矩形框能夠用widthheightbackgrond-color來表現,也能夠用heightborder-leftborder-rightborder-color來表現。咱們用::before::after僞類來分別當一個矩形框,而後進行旋轉便可獲得叉號。orm

咱們用添加類的形式插入叉號,當咱們須要插入叉號時,咱們額外添加一個<i>標記,並添加類icon-crossblog

第一步,設置圖標尺寸。get

.icon-cross{
  width: 20px;
  height: 20px;
  position: absolute;  /*方便相對於父元素進行定位*/
}

第二步,設置僞類,畫叉號。it

.icon-cross::before,
.icon-cross::after{
  content: "";
  position: absolute;  /*方便進行定位*/
  height: 16px;
  width: 1.5px;
  top: 2px;
  right: 9px;  /*設置top和right使圖像在20*20框中居中*/
}
.icon-cross::before{
  transform: rotate(45deg);  /*進行旋轉*/
}
.icon-cross::after{
  transform: rotate(-45deg);
}

爲了讓矩形框有必定圓角好看點,可在僞類樣式中追加border-radius: 1px;。另外,爲了使20*20的框能在父元素中垂直居中,咱們給.icon-cross追加樣式top: 50%; margin-top: -10px;。上邊距爲父元素高度的50%,而後再上移10px,這樣就垂直居中了哦。(10px爲自身高度一半。若是圖標高度是18px,那麼就是上移9px。)io

要設置在父元素中的水平位置,可設置leftrightform

爲了能根據父元素進行定位,父元素務必position:relative||absolute;class

還要注意一點,因爲咱們沒有設置background-color,因此這時候是還啥都看不到。我喜歡在插入圖標時,再另外設置背景顏色,這樣能夠在不一樣地方反覆插入這個圖標,並分別設置不一樣的顏色。固然,你也能夠設置一個顏色做爲默認值。transform

具體的插入圖標示例見開頭的CodePen吧。

補充:我我的比較喜歡用border來當色塊啦,這樣能夠設置僞元素border-color: inherit;,而後直接設置類的邊框顏色就好了。若是是用widthheight來當色塊的話,就只能單獨設置僞類的background-color,以爲麻煩。可是用border來作的話,IE11和Edge在網頁縮放時有時候會在中間多一條縫..很醜陋..

代碼

附上CSS圖標庫代碼。(如今只有三個圖標哈哈)

/*----圖標大小爲20px*20px,已經設置好在父元素中垂直居中,
只需另外設置left或者right來調整水平位置----*/

/*----通用設置----*/
[class|=icon]{  /*全部類名以「icon-」開頭的*/
  width: 20px;
  height: 20px;
  top: 50%;  /*上邊距爲父元素50%*/
  margin-top: -10px;  /*再往上移動自身高度一半,就垂直居中了*/
  position: absolute;  /*有些圖標高度不是20px,那麼margin-top要單獨設置*/
}

[class|=icon]::before,  /*全部類名以「icon-」開頭的僞元素*/
[class|=icon]::after{
  content: "";
  position: absolute;
  height: 0;
  width: 0;
}


/*---------叉號---------*/
.icon-cross::before,
.icon-cross::after{
  height: 16px;
  width: 1.5px;
  top: 2px;
  right: 9px; /*設置right和top使叉號居中*/
  border-radius: 1px;
}
.icon-cross::before{
  transform: rotate(45deg);
}
.icon-cross::after{
  transform: rotate(-45deg);
}

/*----------排行榜----------*/
.icon-ranklist,
.icon-ranklist::before,
.icon-ranklist::after{
  width: 4px;
  border-radius: 1px;
}
.icon-ranklist::before,
.icon-ranklist::after{
  bottom: 0;
  background: inherit;
}
.icon-ranklist{
  height: 18px;
  margin-top: -9px;
  margin-left: 8px;
  margin-right: 8px;  /*這樣排行榜圖標寬度能夠看成20px*/
}
.icon-ranklist::before{
  height: 12px;
  left: -6px;
}
.icon-ranklist::after{
  height: 10px;
  right: -6px;
}

/*----------搜索圖標----------*/
.icon-search::before{
  height: 12px;
  width: 12px;
  border-radius: 12px;
  border: 2px solid;
  top: 1px;
  left: 1px;
  border-color: inherit;
}
.icon-search::after{
  height: 7px;
  border-left: 1.5px solid;
  border-right: 1.5px solid;
  border-radius: 1.5px;
  right: 3px;
  bottom: 0px;
  transform: rotate(-45deg);
  border-color: inherit;
}

存在的問題

最近才發現的,網頁縮放後,圖標會有些變形,好比叉號會一根線長點另外一根線短點,只有在100%大小時才能徹底是你想要的效果,哭...

相關文章
相關標籤/搜索