Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a triangle with CSS that scales to parent div height?

I am currently creating a content block that scales in height dependent on it's content. The block needs to have an arrow at one end that scales to the height of the block.

I would ideally like a pure CSS solution for this if possible. I am currently using the border triangles method: https://css-tricks.com/snippets/css/css-triangle/

This works fine as shown in my fiddle below, but if you increase the height of the div then it doesn't re-scale the triangle to the new height.

https://jsfiddle.net/xq5wwf3h/10/

<div id="triangle-container">
    Some interesting content goes in here!
</div>

body * {
    box-sizing: border-box;
}

#triangle-container {
    position: relative;
    height: 100px;
    width: 100%;
    background: grey;
    margin-left:50px;
    color: #fff;
    padding: 15px;
}

#triangle-container:before {
    content: '';
    position: absolute;
    left: -50px;
    top: 0;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 50px 50px 50px 0;
    border-color: transparent #007bff transparent transparent;
}
like image 570
Antfish Avatar asked Sep 28 '22 16:09

Antfish


1 Answers

I have found a solution (albeit not supported in IE) so it may not be the best way depending on circumstances.

The solution uses the background clip property:

https://jsfiddle.net/xq5wwf3h/32/

body * {
    box-sizing: border-box;
}

#triangle-container {
    position: relative;
    height: 100px;
    width: 100%;
    background: grey;
    margin-left:50px;
    color: #fff;
    padding: 15px;
}

#triangle-container:before {
    content: '';
    position: absolute;
    display: block;
    left: -25px;
    top: 0;
    bottom: 0;
    width: 25px;
    height: 100%;
    background: #007bff;
    -webkit-clip-path: polygon(100% 0, 100% 100%, 0 50%);
    clip-path: polygon(100% 0, 100% 100%, 0 50%);
}
like image 62
Antfish Avatar answered Nov 15 '22 10:11

Antfish