The linear-gradient
background approach posted by Danyal will work, but the problem with that solution is that the angle of the diagonal changes as you resize the screen. To keep the angle consistent as you shrink the screen down, you need a more involved solution.
The basic approach here is to skew each side to the angle you want, then skew the children of each side back in the other direction, so all the content doesn't look like it's at an angle.
If you do that, you'll end up with your background colors not covering the entire width of the container, though – there'll be white space in the top left and bottom right corners – so you also need to oversize each side to fill that space.
You can do that by using calc
with some percentage of width that you want to have the container be plus some extra amount that is equal to how wide that white space is. There is probably some mathematical way to figure out how wide that white space would be based on your container width and the angle of the skew, but I just use dev tools to experiment and figure it out. In the example below, it happens to be 115px
.
Once you've figured out that magic number, you'll do something like:
- Left side
calc([some-percentage] + 115px)
- Right side
calc([some-percentage] + 115px)
- Left side
margin-left: -115px
- Right side
margin-right: -115px
- Left side
padding-left: 115px
- Right side
padding-right: 115px
The negative margin will shift each side off the screen, so that your background covers the entire space. The padding then shifts the content within that side back into the visible center of that side.
Make sure to include overflow: hidden
on the parent.
Here's an example:
.container {
width: 100%;
height: 250px;
display: flex;
overflow: hidden;
}
.left-skew,
.right-skew {
width: calc(50% + 115px);
height: 100%;
transform: skewX(-30deg);
display: flex; /* just for this example */
justify-content: center; /* just for this example */
align-items: center; /* just for this example */
}
.left-unskew,
.right-unskew {
transform: skewX(30deg);
}
.left-skew {
margin-left: -115px;
padding-left: 115px;
background-color: lightgray;
}
.right-skew {
margin-right: -115px;
padding-right: 115px;
background-color: black;
color: white;
}
body {
margin: 0;
}
<div class="container">
<div class="left-skew">
<div class="left-unskew">lorem ipsum dolor sit amet</div>
</div>
<div class="right-skew">
<div class="right-unskew">lorem ipsum dolor sit amet</div>
</div>
</div>