I am trying to get the text decoration to appear from left to right, as if it is being crossed out with a pen.
Is there a way to do this without making changes to the text behind it?
Thanks in advance!
document.querySelector('h1').addEventListener('click', (e) => {
e.target.classList.toggle('strikethrough')
})
.strikethrough {
text-decoration: line-through;
text-decoration-style: wavy;
text-decoration-thickness: 15%;
animation: strike 3s linear;
}
@keyframes strike {
0% {width: 0;}
100% {width: 100%;}
}
<h1>CROSS ME OUT</h1>
CodePudding user response:
If you are willing to accept using a straight line as the strike through (instead of depending on the font's own strikethrough styles), then it is just a matter of overlaying a div on top of the <h1>
element and offsetting it 100% to the side using transform: translateX(-100%)
. We give it a top border whose width is font-size dependent (i.e. use em
units), and a color whose value is dependent on the current font color (i.e. use currentColor
).
You can use CSS transitions set the duration and easing function of the entry of this line. When the .strikethrough
class is added, the offset is simply set to transform: translateX(0)
.
A caveat is that this trick only works for non-breaking lines. If your h1 element will render across multiple lines, then it wouldn’t work.
See proof-of-concept example below:
document.querySelector('h1').addEventListener('click', (e) => {
e.target.classList.toggle('strikethrough')
});
h1 {
display: inline-block;
position: relative;
overflow: hidden;
}
h1::after {
position: absolute;
top: calc(50% - 0.05em);
left: 0;
width: 100%;
content: '';
display: block;
border-top: 0.1em solid currentColor;
transform: translateX(-100%);
transition: transform .25s ease-in-out;
}
h1.strikethrough::after {
transform: translateX(0);
}
<h1>CROSS ME OUT</h1>