Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw triangle in corner of div

Tags:

html

css

I'd like to draw some kind of triangle in the corner of a div. Because I don't want to use "px" I'd like to achieve the same result also with percentage values.

This is what it should looks like:

img

.container {
  position: absolute; 
  top: 5%; 
  left: 5%; 
  width: 60%; 
  height: 30%; 
  background: black; 
  color: white;
  border-radius: 12px;
  overflow: hidden;
}

.triangle {
  position: relative;
  top: 10%;
  left: 90%;
  width: 10%;
  height: 10%;
  -webkit-transform: rotate(45deg);
  background: green;
}
<div class="container">
  <div class="triangle"></div>
</div>

Any help would be very appreciated. Thanks in advance!!

like image 410
Jonas0000 Avatar asked Feb 24 '18 11:02

Jonas0000


1 Answers

You can use position: absolute on triangle element and set top and right properties to 0.

.container {
  position: absolute;
  top: 5%;
  left: 5%;
  width: 60%;
  height: 30%;
  background: black;
  color: white;
  border-radius: 12px;
  overflow: hidden;
}

.triangle {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 30px 30px 0;
  border-color: transparent #608A32 transparent transparent;
  right: 0;
  top: 0;
  position: absolute;
}
<div class="container">
  <div class="triangle"></div>
</div>

You can also just use pseudo-element with absolute position for triangle.

.container {
  position: relative;
  width: 300px;
  height: 70px;
  background: black;
  border-radius: 12px;
  overflow: hidden;
}

.container:after {
  content: '';
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 30px 30px 0;
  border-color: transparent #608A32 transparent transparent;
  right: 0;
  top: 0;
  position: absolute;
}
<div class="container"></div>

Below is another example with triangles in all corners.

.all_triangles_container {
  position: relative;
  width: 300px;
  height: 70px;
  background: black;
  overflow: hidden;
}

.triangle {
  width: 0;
  height: 0;
  border-style: solid;
  position: absolute;
}

.triangle_tl {
  border-width: 0 0 30px 30px;
  border-color: transparent transparent transparent green;
  left: 0;
  top: 0;
}

.triangle_tr {
  border-width: 0 30px 30px 0;
  border-color: transparent red transparent transparent;
  right: 0;
  top: 0;
}

.triangle_br {
  border-width: 30px 30px 0 0;
  border-color: transparent yellow transparent transparent;
  right: 0;
  bottom: 0;
}

.triangle_bl {
  border-width: 0 30px 30px 0px;
  border-color: transparent transparent purple transparent;
  left: 0;
  bottom: 0;
}
<div class="all_triangles_container">
  <div class="triangle triangle_tl"></div>
  <div class="triangle triangle_tr"></div>
  <div class="triangle triangle_br"></div>
  <div class="triangle triangle_bl"></div>
</div>
like image 69
Nenad Vracar Avatar answered Sep 17 '22 14:09

Nenad Vracar