CSS slanted box with ::before and ::after

I remember back when angled corners and border radius caused a developer to break out in a cold sweat. 'Time to break out the image slices', we all heard.

There are quite a few methods for doing angles in CSS with borders and the ::before pseudo selectors. More recently, transforms have appeared and all the modern browsers support them.

Some solutions use perspective and rotate in the transform to get the angle, this little trick uses the skew transform to get a CSS slanted box (note the footnote in regards to skew being removed from some implementations).

/* garish colours used to show the elements */

.box {
background-color : red;
position : relative;
display : block;
height : 50px;
width : 200px;
text-align : center;
margin : 0 auto;
}

.box p {
padding : 0px;
}

.box::before {
content: '';
height: 50px;
width: 50px;
background-color: blue;
position: absolute;
top: 0;
left: -50px;
transform: skewX(45deg);
transform-origin: top;
-webkit-transform: skewX(45deg);
-webkit-transform-origin: 0 0;
}

.box::after {
content: '';
height: 50px;
width: 50px;
background-color: green;
position: absolute;
top: 0;
right: 0;
left: auto;
transform: skewX(45deg);
transform-origin: top;
-webkit-transform: skewX(45deg);
-webkit-transform-origin: 0 0;
}

see the fiddle and modify as you wish. Have a solution without heights ? - let everyone know in the comments!

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments