製作圓形頭像看似簡單,但當圖片的寬高不相等時,就需要多花點心思。以下分兩種情況說明。
假設原圖為 width:300px、height:300px,要把它變成寬高 100px 的圓形頭像:
img{width:100px; height:100px; border-radius:50%;-webkit-border-radius:50%;-moz-border-radius:50%;}
例如 width:400px、height:600px。此時可以善用百分比讓頭像具備響應式效果。
解法:先在外層包一個 div,把 div 變成圓角,再讓圖片以 100% 填充進去。
<div class="imgheadborder">
<img class="imghead" src="images/thumsb/thumsb_pic2.jpg" />
</div>
CSS 代碼:
.imgheadborder{ width:10.9%; padding-top:10.9%; margin-right:2.8%; border-radius:50%;-webkit-border-radius:50%;-moz-border-radius:50%; position:relative;}
.thumsbcount .imghead{position:absolute;left:0px;top:0px; border-radius:50%;-webkit-border-radius:50%;-moz-border-radius:50%; width:100%;height:100%;z-Index:-1;}
關鍵在於用 padding-top 撐出正方形比例,再讓圖片絕對定位填滿容器,如此一來無論原圖寬高比為何,都能呈現標準的圓形頭像。