Reputation: 9672
To create background patterns (triangle, trapezoid, etc.) I see a lot of devs relying on SVGs. Today, I came across a technique that I don't quite understand.
By scaling a shape like this:
and applying height: 100%
as well as transform-origin
a triangle is created. The start-point of the triangle is always the lower-left corner of the containing element. The result is nice and responsive, but I have no idea why this works from a geometric perspective.
I created a Codepen to demonstrate.
.shape {
position: absolute;
width: 100%;
}
.shape-img {
padding-bottom: 10rem;
overflow: hidden;
background: yellow;
position: inherit;
width: inherit;
}
.shape-img > svg {
position: inherit;
height: 100%;
width: inherit;
transform: scale(2);
transform-origin: top center;
}
.position-relative {
position: relative;
}
<div class="position-relative">
<div class="shape">
<div class="shape shape-img">
<svg viewBox="0 0 100 50" preserveAspectRatio="none"><path d="M0 25h25L75 0h25v50H0z" fill="currentColor"></path></svg>
</div>
</div>
</div>
<br />
<br />
<!--
<svg viewBox="0 0 100 50" preserveAspectRatio="none"><path d="M0 25h25L75 0h25v50H0z" fill="currentColor"></path></svg>
-->
1. How does this approach ensure that the lower-left corner the bottom of the containing element?
2. How does this approach ensure that the user sees a triangle shape regardless of the screen-size?
Upvotes: 1
Views: 269
Reputation: 272648
Here is an easier idea with the same SVG and only one div:
.box {
height:200px;
background:
url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 50" preserveAspectRatio="none"><path d="M0 25h25L75 0h25v50H0z" fill="currentColor"></path></svg>')
top/ /* place it at the top center (no need "center" because it's by default) */
200% 200%, /* width height (twice bigger as the container*/
yellow; /* background color */
}
<div class="box"></div>
To understand the scale effect see the below:
.box {
border:5px solid red;
margin:50px auto;
width:200px;
height:100px;
position:relative;
}
.box svg {
position:absolute;
z-index:-1;
top:0;
left:0;
width:100%;
height:100%;
transform:scale(2);
transform-origin:top center;
}
<div class="box">
<svg viewBox="0 0 100 50" preserveAspectRatio="none"><path d="M0 25h25L75 0h25v50H0z" fill="currentColor"></path></svg>
</div>
By the way, you can use an easier SVG where you have only a triangle shape:
.box {
height:200px;
background:
url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1" preserveAspectRatio="none"><polygon points="0,1 1,0 1,1" fill="black"/></svg>'),
yellow;
}
<div class="box"></div>
Upvotes: 2