5

css实现三角形

 2 years ago
source link: https://segmentfault.com/a/1190000040719403
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在实际编程中我们经常会遇到下拉菜单的下三角和一些特殊的图形,那么这些如何用css来实现呢?

例1

例2

例3

仔细想想,原理非常简单,利用CSS的border以及它的属性值transparent来实现三角形,其中最主要的是要明白由于div的高度跟宽度都为0,margin,padding也为0,所以元素框的大小就是他的border的叠加,由于相邻border会重叠,故存在内容宽高时其实任意一边存在的border都是梯形的,当div内容宽高为0时,border就表现为三角形,将四个border的颜色设置为transparent表示边框透明,而将右边框颜色再设置为红色就发现三角形出现了,其实这个三角形是你设置颜色的边框。

<style>
    div {
        width: 0;
        height: 0;
        border-top: 40px solid transparent;
        border-left: 40px solid transparent;
        border-right: 40px solid transparent;
        border-bottom: 40px solid #ff0000;
    }
    </style>
</head>
<body>
  <div></div>
</body>

展示结果:

如果想要不同方向的三角形,只需要改变所需的边框颜色,另外三条边改为transparent(透明)。那么我们就能很简单的实现例1和例3的效果

一些不规则的三角形只需要改变边框的宽度就可以得到不同形状的三角形

<style>
        div{
            width: 0px;
            height: 0px;
            border-width: 0px 0px 200px 100px;
            border-style: solid;
            border-bottom-color:green ;
            border-left-color:transparent;
        }
</style>
</head>
<body>
  <div></div>
</body>

展示结果:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK