Reputation: 85
I am trying to build a CSS triangle that resizes itself according to the width of the parent.
Currently I have given custom size for the triangle I have created so that on resizing, the triangle starts to come outside of the parent. But I need the triangle to stay inside the parent on resizing but take full width. Please help. Thank you.
Here is my HTML and CSS.
.triangle-container{
width:50%;
height:200px;
background-color: #000000;
}
.triangle{
width:0;
height:0;
border-left:167px solid rgba(0,0,0,0);
border-right:167px solid rgba(0,0,0,0);
border-top:100px solid red;
}
<div class="triangle-container">
<div class="triangle"></div>
</div>
Upvotes: 3
Views: 2955
Reputation: 64164
One posibility: use a multiple background to create the triangle. The element is set to take half the height of the parent, and the full width
.triangle-container{
width:50%;
height:200px;
background-color: #000000;
}
.triangle{
width:100%;
height:50%;
background-image: linear-gradient(to top right, transparent 50%, red 50%),
linear-gradient(to top left, transparent 50%, red 50%);
background-size: 50.2% 100%;
background-repeat: no-repeat;
background-position: top left, top right;
}
<div class="triangle-container">
<div class="triangle"></div>
</div>
Upvotes: 4
Reputation: 1615
K this isn't a triangle but it looks like you trying to make an envelope shape... so here is how I would do it, change border etc. accordingly:
.triangle-container {
width: 50%;
height: 200px;
padding-left: 25%;
padding-top: 25%;
overflow: hidden;
background-color: #000000;
}
.triangle {
width: 50%;
height: 0;
margin-left: -500px;
margin-top: -500px;
border-left: 500px solid transparent;
border-right: 500px solid transparent;
border-top: 500px solid #4679BD;
}
<div class="triangle-container">
<div class="triangle"></div>
</div>
EDIT: For a triangle shape change following css properties of triangle-container to:
width: 100%;
padding-left: 50%;
padding-top: 50%;
and triangle:
width:0;
Upvotes: -1
Reputation: 489
You can try using viewport relative units, something in this sense:
.triangle-container{
width:50%;
height:500px;
background-color: #000000;
position: relative;
overflow: hidden;
}
.triangle{
width:50vw;
height:50vw;
position: absolute;
top: -50vw;
transform: rotate(45deg);
background: purple;
}
Preview: http://codepen.io/anon/pen/LEdREr?editors=110
Upvotes: 0