如何通過CSS樣式繪製三角形,0基礎學前端專案案例開發之HMTL+CSS專案實戰系列
阿新 • • 發佈:2022-03-11
各位同學們大家好,近期為大家開設一個系列的實戰課程,通過HMTL5+CSS3做網際網路大廠常用的實戰案例,當你學會之後,您就可以組合成為一個網站專案了!
好廢話不多說,今天帶著大家繪製一個小米、百度、網易等網站常用的三角形指示符號!好,我們來進入今天的內容知識體系!
第一步 繪製一個正方形
程式碼:
<style type="text/css"> .triangle{ width:50px; height:50px; background-color: red; } </style> <body> <div class="triangle"></div> </body>
執行顯示效果:
第二步:給正方形新增4個方向不同顏色的邊框
程式碼:
<style type="text/css"> .triangle{ width:50px; height:50px; background-color: red; border-top:50px solid blue;/*上邊框線*/ border-right:50px solid yellow;/*右邊框線*/ border-bottom:50px solid greenyellow;/*下邊框線*/ border-left:50px solid orange;/*左邊框線*/ } </style> <body> <div class="triangle"></div> </body>
程式碼執行效果
第三步:把.triangle的高度和寬度設定為0
程式碼:
<style type="text/css"> .triangle{ /*--更改程式碼處--*/ width:0px; height:0px; background-color: red; border-top:50px solid blue;/*上邊框線*/ border-right:50px solid yellow;/*右邊框線*/ border-bottom:50px solid greenyellow;/*下邊框線*/ border-left:50px solid orange;/*左邊框線*/ } </style> <body> <div class="triangle"></div> </body>
程式碼執行效果:
第四步:設定三個邊框顏色為透明,實現三角形
程式碼:
<style type="text/css"> .triangle{ width:0px; height:0px; /*background-color: red;*/ border-top:50px solid blue;/*上邊框線*/ border-right:50px solid transparent;/*右邊框線*/ border-bottom:50px solid transparent;/*下邊框線*/ border-left:50px solid transparent;/*左邊框線*/ } </style> <body> <div class="triangle"></div> </body>
執行效果
注意:
我們把右,下,左邊框的顏色設定為transparent 透明,這樣就能看到上在的三角形了。當然我們需要那個三角形,我們就可以把另外三個邊框的顏色設定為transparent透明。同時把盒子最開始加的background-color:red; 註釋掉,只留下三角形。
第五步 優化下程式碼,使程式碼更簡潔
程式碼
<style type="text/css"> .triangle{ width:0px; height:0px; /* background-color: red; */ border:50px solid transparent;/*把四個方向的邊框全設為透明*/ border-top:50px solid blue;/*單獨控制上邊框*/ /* border-right:50px solid transparent; border-bottom:50px solid transparent; border-left:50px solid transparent; */ } </style> <body> <div class="triangle"></div> </body>
執行效果
我們可以把.triangle的邊框的顏色全設定為透明的 border:50px solid transparent,然後單獨設定某一條邊框的樣式(border-top 、border-bottom 、border-right、border-left)
如有相關前端方面的技術問題或者需要本節課的視訊教程以及相關基礎教程 ,歡迎新增我,我會定期在群裡給大家分享最新技術和解答問題 。