Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to cut out a triangle section from a div using CSS?

Tags:

css

Is it possible to cut a triangle from a <div> like in the picture below?

The background is actually not just colour, but in my case is a blurred picture, so I can’t simply cover the green <div> with a brown triangle image. Is there some other CSS way to achieve this effect? Thanks.

example of div cut

like image 787
fillky Avatar asked Oct 06 '13 21:10

fillky


People also ask

How do you add a triangle to a div?

Add a triangle to end of div You can use :after selector to add a style to the end of a div. When adding an arrow to bottom we need to keep the top border and make other borders transparent. In this div, the width has been set as 100px. Then the left and the right border have to be half of size of the div.

How do you make a triangle with corners in CSS?

You can use position: absolute on triangle element and set top and right properties to 0. You can also just use pseudo-element with absolute position for triangle.


1 Answers

The illusion of it is possible: http://jsfiddle.net/2hCrw/4/

Tested with: IE 9, 10, Firefox, Chrome, Safari on PC and iPad.

  • ::before and ::after pseudo elements are skewed to provide a side of the triangle each.
  • Wrapper used for clipping skewed pseudo elements. You may be able to avoid this by using your outer container as the wrapper.
  • Elements can still be styled with borders, shadows, etc.
  • Anything underneath will show through properly.

Demo with borders and drop shadow: http://jsfiddle.net/2hCrw/8/

This demo also adds a tweak for iPad with Retina to prevent a gap between the element and the pseudo elements (either caused by drop shadow bleed or sub-pixel rendering behavior).

<div id="wrapper">
    <div id="test">test</div>
</div>


#wrapper {
    overflow: hidden;
    height: 116px;
}
#test {
    height: 100px;
    background-color: #ccc;
    position: relative;
}
#test::before {
    content:"";
    position: absolute;
    left: -8px;
    width: 50%;
    height: 16px;
    top: 100px;
    background-color: #ccc;
    -webkit-transform: skew(-40deg);
    -moz-transform: skew(-40deg);
    -o-transform: skew(-40deg);
    -ms-transform: skew(-40deg);
    transform: skew(-40deg);
}
#test::after {
    content:"";
    position: absolute;
    right: -8px;
    width: 50%;
    height: 16px;
    top: 100px;
    background-color: #ccc;
    -webkit-transform: skew(40deg);
    -moz-transform: skew(40deg);
    -o-transform: skew(40deg);
    -ms-transform: skew(40deg);
    transform: skew(40deg);
}

As an alternative, you can use a transparent image and "extend" the element above it with pseudo elements. I have answered a similar question regarding a circle cut from an element and show support options down to IE7 (as well as future options for true clipping/masking in CSS).

like image 197
Tim M. Avatar answered Dec 11 '22 22:12

Tim M.