使用3D緞帶形狀的標籤是常見的一個設計模式,用在商品折扣、文章標題或網站推薦信息上,
來突出顯示重點內容,吸引用戶視覺焦點。實現的方法有2種,一種是使用背景圖片,一種是使用三角形的CSS3僞元素。
本文介紹第2種方法,使用一個最簡化的實例來講解如何實現這個效果:
上面的界面是一張簡化的商品卡片,包含標籤和商品描述,我們使用h2元素來容納標籤,HTML代碼如下:
<div class="fancy">
<h2>
<span class="ribbon-center">50% OFF!</span>
</h2>
<p>
<img src="/uploads/160501/glass.jpg">
Check out these killer deals from Oakley!
Get an additional 50% off sale items for a limited time.
</p>
</div>
接下來給卡片和商品描述添加樣式,來限定高寬和間距:
.fancy {
width: 340px;
margin: 20px auto 20px auto;
background: #E7E7E7;
padding: 15px;
}
.fancy p {
padding-top: 10px;
margin: 5px 0;
line-height: 1.5;
}
.fancy img {
width: 340px
}
現在頁面看起來像上面這樣,接下來就是要給標籤(h2元素)添加樣式,一個是背景色,一個是左邊的3D摺紙效果。
折邊效果其實就是給h2的左下角拼接一個三角形的元素,我們使用僞元素來實現,代碼如下:
.fancy h2 {
font-style: italyc;
line-height: 1;
padding: 5px 0;
color: #FFF;
margin: 0;
width: 205px;
left: -35px;// 相對卡片向左偏移35px
background-color: #e54439;
position: relative;
z-index: 6;
}
.fancy h2:after {// 定義一個斜三角形
content: "";
width: 0;
height: 0;
position: absolute;
font-size: 0;
line-height: 0;
z-index: 5;
border-top: 0 solid transparent;
border-bottom: 15px solid transparent;
bottom: -15px;
}
.fancy h2:after {
border-right: 20px solid rgb(230, 107, 97);
left: 0;
}
.fancy h2 .ribbon-center {
display: block;
padding: 10px 0;
background-color: #e54439;
}
其中h2的left屬性爲-35px,這使得h2相對卡片向左偏移35px,這樣就看起來像是包裝在卡片外面。
h2:after僞元素是一個常用的三角形定義(寬高爲0的元素加上border調整可以實現各種三角形形狀),這樣就可以了。