How do I draw a diagonal div
in CSS? Google only reveals how to draw diagonal "lines", but I could not understand how to make that for div
's.
In the pic below, the blue part is the div
:
width: 100px; The fun thing though, is that you can turn it into a diagonal just by changing the degree of rotation! To move the line around the page you can add the parameters translateX and translateY to the transform property. This will move the line along the X and Y axis respectively.
A diagonal is made out of a straight line that's set at an angle instead of straight up or across. If you picture a square and draw a line connecting the opposite corners, that's a diagonal line. You'll find diagonal lines in geometry, and also in the world around you.
From a CSS point of view, a diagonal line is nothing but a horizontal line which is rotated at +45 or -45 degrees angle. So, to draw a diagonal line in CSS, we have to simply rotate a normal horizontal line at an angle of + or – 45 degrees. The rotation in CSS is done using the transform property.
You could use CSS3 transform skewY()
function with positive value for the parent and negative value for the child wrapper element to achieve the effect.
.parent {
-webkit-transform: skewY(-5deg);
-moz-transform: skewY(-5deg);
-ms-transform: skewY(-5deg);
-o-transform: skewY(-5deg);
transform: skewY(-5deg);
}
.parent > .child {
-webkit-transform: skewY(5deg);
-moz-transform: skewY(5deg);
-ms-transform: skewY(5deg);
-o-transform: skewY(5deg);
transform: skewY(5deg);
}
WORKING DEMO.
From the spec:
skewY()
specifies a 2D skew transformation along the Y axis by the given angle.
It's worth noting that the using skewY()
won't change the width of the transformed elements.
Also mind the child selector. It's better to use direct child selector .parent > .child
rather than descendant selector to negate the transform on the child element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With