Reputation: 393
Not sure if this is possible, but how would I create a 1px diagonal line that goes from top left of element to bottom right, no matter the width and/or height of that element?
Upvotes: 6
Views: 8941
Reputation: 1725
You can do this in multiple ways.
1) background image
1.1) SVG
You can create an svg direct as inline code and use it for drawing the line. Using this you can achiev nice effects like shadow, gradient, dotted line, ... and much more. It is also posible to use a svg inside the css background-image element.
<svg style='width: 100%; height: 100%;'>
<line x1="0" y1="100%" x2="100%" y2="0"
style="stroke:rgb(0,0,0);stroke-width:1"/>
</svg>
1.2) fix image (png, jpg, ...)
You can also use a simple image as background image on full div.
2) create linear background gradient
.testDiv {
width: 300px;
height: 300px;
background:linear-gradient(to bottom right, transparent calc(50% - 1px), black calc(50% - 1px), black 50%, transparent 50%);
}
How does this works?
(read more here)
3) rotated inner div (only on square divs)
when resizing the testDiv, the line should stay a diagonal.
.testDiv{
width: 600px;
height: 600px;
background-color: gray;
}
.lineDiv {
position: relative;
top: 29%;
left: 29%;
width: 142%;
height: 142%;
border-left: solid thin blue;
transform: rotate(45deg);
}
How does this works?
-> 142 = sqrt(100^2 + 100^2) (see phytagoras)
Upvotes: 21
Reputation: 105843
background-image from a linear gradient should do :
body {
background:linear-gradient(to bottom right, transparent calc(50% - 1px), black calc(50% - 1px), black 50%, transparent 50%) yellow;
/*demo purpose */
height:50%;
width:50%;
margin:auto;
}
html {
display:flex;
height:100vh;
background:white;
}
/* end demo purpose */
run snippet full page and resize window's browser to test behavior
Upvotes: 4