How to make a triangle with CSS

Some times we need to make a triangle after some elements in the page, for example, simulating a kind of dropdown menu.


The triangle above is made by div and CSS.
Here is the code:
<div class="example-btn">
</div>
<style>
.example-btn{
background-color: transparent;
height: 0px;
width: 0px;
padding: 0px;
content: " ";
border-width:25px 25px 0px 25px;
border-color: #000000 transparent;
border-style: solid;
}
</style>

The code is very simple, I believe everyone knows CSS can read this code -- it is an empty div with 0 width and 0 height and borders. But how does this form an triangle?

If we change the code above like this:
<div class="example-btn">
</div>
<style>
.example-btn{
background-color: transparent;
height: 0px;
width: 0px;
padding: 0px;
content: " ";
border-width:25px 25px 25px 25px;
border-color: #000000;
border-style: solid;
}
</style>

We will get this shape:

It is easy to understand -- an div with black borders around it and because the div is empty, the borders fill all the space and form a solid black square.

Then, let's set left/right border to transparent:
<div class="example-btn">
</div>
<style>
.example-btn{
background-color: transparent;
height: 0px;
width: 0px;
padding: 0px;
content: " ";
border-width:25px 25px 25px 25px;
border-color: #000000 transparent;
border-style: solid;
}
</style>

And we will get:
The right and left borders are set to transparent so we can only see the top and bottom borders. In this step, you may be surprised at the shape of top and bottom borders. Because the div is empty and the size is 0, all the borders are compressed together. The joint of the two neighboring borders are 45 degree of an angle. And this is the fundamental of making a triangle with CSS.

Finally, wipe out the bottom border:
<div class="example-btn">
</div>
<style>
.example-btn{
background-color: transparent;
height: 0px;
width: 0px;
padding: 0px;
content: " ";
border-width:25px 25px 0px 25px;
border-color: #000000 transparent;
border-style: solid;
}
</style>

And we get the triangle we want:

评论

此博客中的热门博文

Openwrt路由器上配置shadowsocks透明代理+gfwlist(PAC)

Configure shadowsocks transparent proxy + gfwlist(PAC) on OpenWRT Router

Using Haproxy + shadowsocks (ha + ss) to setup multi ss backend and load balance