CSS三角形的实现原理及运用(各种角度)

576 阅读2分钟

原理

css盒模型

一个盒子包括: margin+border+padding+content– 上下左右边框交界处出呈现平滑的斜线.

利用这个特点, 通过设置不同的上下左右边框宽度或者颜色可以得到小三角, 小梯形等.– 调整宽度大小可以调节三角形形状.

示例1

一般情况下, 我们设置盒子的宽高度, 及上下左右边框, 会呈现如下图·

#test1 {
    height:20px;
    width:20px;
    border-color:#FF9600 #3366ff #12ad2a #f0eb7a;
    border-style:solid;
    border-width:20px;
}

示例2

在上面基础上, 我们把宽高度都设为0时, 会呈现上述的边界斜线.·

#test2 {
    height:0;
    width:0;
    overflow: hidden; /* 这里设置overflow, font-size, line-height */
    font-size: 0;     /*是因为, 虽然宽高度为0, 但在IE6下会具有默认的 */
    line-height: 0;  /* 字体大小和行高, 导致盒子呈现被撑开的长矩形 */
    border-color:#FF9600 #3366ff #12ad2a #f0eb7a;
    border-style:solid;
    border-width:20px;
}

如下,就是利用上面设置宽高为0的情况,来进行三角的绘制

上三角

#triangle-up {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 100px solid red;
}

下三角


#triangle-down {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-top: 100px solid red;
}

左三角


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

右三角


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

左上三角


#triangle-topleft {
    width: 0;
    height: 0;
    border-top: 100px solid red;
    border-right: 100px solid transparent;
}

右上三角


#triangle-topright {
    width: 0;
    height: 0;
    border-top: 100px solid red;
    border-left: 100px solid transparent; 
}

左下三角


#triangle-bottomleft {
    width: 0;
    height: 0;
    border-bottom: 100px solid red;
    border-right: 100px solid transparent;
}

右下三角


#triangle-bottomright {
    width: 0;
    height: 0;
    border-bottom: 100px solid red;
    border-left: 100px solid transparent;
}