【CSS】画三角形

发布时间 2023-09-05 21:07:36作者: zjy4fun

<html>
    <head>
        <title>CSS 绘制三角形</title>
    </head>
    <body>
        <div>
            <h1>实心三角形</h1>
            <div class="filled-triangle-1"></div>
            
            <div>
                <h1>等边三角形</h1>
                <div class="filled-triangle-2"></div>
            </div>

            <h1>聊天气泡</h1>
            <div class="chat-triangle">yo, bro!</div>
        </div>
    </body>

    <style>
        .filled-triangle-1 {
            width: 0;
            height: 0;
            border: 50px solid red;
            border-bottom: 50px solid cyan;
            border-right: 50px solid yellow;
            border-top: 50px solid green;
        }

        /* 等边三角形 */
        .filled-triangle-2 {
            width: 0;
            height: 0;
            border-left: 50px solid transparent; /* transparent 表示透明 */
            border-right: 50px solid transparent;
            border-bottom: 87px solid #ff0000; 
        }

        .chat-triangle {
            position: relative;
            width: 300px; 
            height: 60px; 
            padding: 10px;
            border: 1px solid cyan; 
            border-radius: 8px;
        }
        /* 深色三角形 */
        .chat-triangle::before {
            position: absolute;
            top: 34px; 
            left: -10px; 
            border-top: 6px solid transparent; 
            border-bottom: 6px solid transparent; 
            border-right: 10px solid cyan;
            content: '';  
        }
        /* 画一个白色的三角形盖上去,错位 2 个像素 */
        .chat-triangle::after{
            position: absolute; 
            top: 34px; 
            left: -8px; 
            border-top: 6px solid transparent; 
            border-bottom: 6px solid transparent; 
            border-right: 10px solid #fff;
            content: '';  
        }
    </style>
</html>