文字量に応じてグラデーションの長さを変える

背景に写真を敷いていて、文字の可読性を上げるために半透明黒のグラデーションを敷くようなケース。文字量に応じて濃い部分の長さを調整したいという主旨。


HTML


<div class="p-header">
  <h1 class="p-header__heading">
    <span class="p-header__headingInner"><span>吹矢サークル 遊矢家(ゆうやけ)</span></span>
  </h1>
</div>

CSS


.p-header {
	&__headingInner {
		--gradient-stop-center: 60%;
		background: linear-gradient(to right, rgba(0,0,0,.58) 60%, transparent 95%);  // IE11
		background: linear-gradient(to right, rgba(0,0,0,.58) var(--gradient-stop-center), transparent 100%);
		color: #fff;
		@include mq-min(768) {
			--gradient-stop-center: 30%;
			--gradient-stop-end: 50%;
			background: linear-gradient(to right, rgba(0,0,0,.58) 30%, transparent 50%);  // IE11
			background: linear-gradient(to right, rgba(0,0,0,.58) var(--gradient-stop-center), transparent var(--gradient-stop-end));
		}
	}
}

JavaScript


if (window.CSS && CSS.supports('color', 'var(--fake-var)')) {
    const $headingInner = $('.p-header__headingInner');
    const $headingText = $('.p-header__headingInner span');
    const $content = $('.c-content');
    $(window).on('load resize', () => {
        window.requestAnimationFrame(() => {
            const totalWidth = window.innerWidth;
            const contentWidth = $content.eq(0).width();
            const textWidth = $headingText.width();
            const widthFromLeftToTextEnd = (totalWidth - contentWidth) / 2 + textWidth;
            const percentage = widthFromLeftToTextEnd / totalWidth * 100;
            $headingInner[0].style.setProperty('--gradient-stop-center', percentage + '%');
            $headingInner[0].style.setProperty('--gradient-stop-end', (percentage + 20 > 100 ? 100 : percentage + 20) + '%');
        });
    });
}