1. 程式人生 > 實用技巧 >用純 CSS 建立一個三角形

用純 CSS 建立一個三角形

參考自網路資料(原文第 4 點): https://juejin.im/post/5cb92d9a5188254160581b87

1. 實現方式

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div></div>
    </
body> </html>
引用樣式的 html
div{
    width: 0;
    height: 0;
    border-top: 50px solid transparent;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 50px solid red;
}

2. 一步一步理解建立原理

建立一個正方形寬高為 100px,背景顏色為黑色

div{
    width: 100px;
    height: 100px
; background-color: black; }

設定上邊框

div{
    width: 100px;
    height: 100px;
    background-color: black;
    border-top: 50px solid yellow;       
}

設定左邊框

div{
    width: 100px;
    height: 100px;
    background-color: black;
    border-top: 50px solid yellow;
    border-left: 50px solid green;    
}

設定右邊框

div{
    width: 100px;
    height: 100px;
    background-color: black;
    border-top: 50px solid yellow;
    border-left: 50px solid green;
    border-right: 50px solid blue;    
}

設定下邊框

div{
    width: 100px;
    height: 100px;
    background-color: black;
    border-top: 50px solid yellow;
    border-left: 50px solid green;
    border-right: 50px solid blue;
    border-bottom: 50px solid red;      
}

將盒子寬高設定為 0

div{
    width: 0;   
    height: 0;   
    border-top: 50px solid yellow;
    border-left: 50px solid green;
    border-right: 50px solid blue;
    border-bottom: 50px solid red;
}

將上、左、右邊框顏色設定為透明 transparent

div{
    width: 0;
    height: 0;
    border-top: 50px solid transparent;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 50px solid red;
}