I want to have text (in this case inside a <h1>
) to have colorful background, where the right and left boundaries are slanted. Something like this:
I know that I should do this by setting a backround like linear-gradient(102deg, #ffffff00 5%, lightblue 5% 95%, #ffffff00 95%);
(which I used for this example), but I cannot get the left and right boundaries right. I think the problem is that I to need set start and stop values for the gradient (5% and 95% in this example), but that means that depending on the length of the text, the transition is "somewhere".
h1 span {
background: linear-gradient(102deg, #ffffff00 5%, lightblue 5% 95%, #ffffff00 95%);
padding-left: 0.8rem;
margin-right: 1rem;
}
<h1> <span> This is a title </span> </h1>
Note that I manually had to play around with padding-left
and margin-right
to somehow make it appear okayish (even though there is way too much space right of "title"?).
If I make the text longer, the same CSS produces this:
This is probably because 5% and 95% of the <span>
‘s width are now at different positions, right?
What I would want is a solution that:
- Always works idenpentently of the length of the text
- Does not skew the text itself
- Works with multiline text
- Does not cut off the slanted background (see the right boundary of the second example above)
- Has a little space between the first letter and the left boundary of the background box, and the same amount of space between the last letter and the right boundary of the background box.
I tried setting the boundaries for the linear-gradient
to 0.001%
and 99.999%
or something, but that essentially removes the slanted borders:
4
Answers
You can use skew property of transofrm.
Please replace background colour with your gradients.
Hope this helps.
What you are locking for is the property
transform: skew()
.Just give the container its value and its child elements the opposite one.
Just use
padding-left
andpadding-right
5%
, because that’s the padding of thelinear-gradient
too.