第一次看到 CSS 形狀是在 N 年前的谷歌首頁頂部產品導航欄里面有一個向下的三角圖標浊仆,一開始以為是一個小的圖片杖小,后來一想按照谷歌的作風頁面肯定是越簡潔越好列林,在首頁只可能放一個 logo 圖片不可能為了那么一個小小的圖標再多添加一張终吼,然后我就查看了那個部分的源碼贞盯,果然是用純 CSS 寫的:
width: 0px;
height: 0px;
border-top: 3px solid #c0c0c0;
border-left: 3px solid transparent;
border-right: 3px solid transparent;
在 width 和 height 都為 0px 的情況下為什么僅用 border 就能實現一個三角形狀呢音念?如果我們把四個邊框都設置成不同的顏色就能一目了然了:
width: 0px;
height: 0px;
border-top: 50px solid red;
border-left: 50px solid blue;
border-right: 50px solid yellow;
border-bottom: 50px solid green;
這時如果把左邊框和右邊框顏色都設為透明,下邊框可以去掉躏敢,就變成了一個向下的紅色箭頭:
width: 0px;
height: 0px;
border-top: 50px solid red;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
改變一下邊框的寬度就能變成各種形狀的三角形闷愤,比如等邊三角形:
width: 0px;
height: 0px;
border-top: 86.6px solid red;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
如果把左邊框去掉會變成這個形狀:
width: 0px;
height: 0px;
border-top: 50px solid red;
border-right: 50px solid transparent;
這些只是最基本的 CSS 形狀,好處是兼容各種瀏覽器件余,但是不能實現更復雜的形狀讥脐,如果要更復雜的形狀就要用到 ::before 和 ::after 這樣的偽元素遭居,下次會詳細講述。