[css] filling text color

Phillip Summer·2024년 5월 16일

강조강조 문구

이런 텍스트가 있다고 할 때, 강조 색상을 애니메이션 효과로 채우는 방법에 대한 글입니다.

🔰 html

<h1><strong data-text="안녕하십니까">안녕하십니까</strong> 환영합니다.</h1>

❗❗ html 참고사항

  • 위 문구에서 strong 태그를 채운다고 예를 들어봅시다.
  • data-text이라는 속성은 가상요소 content에서 쓰기 위한 것입니다. 쓰지 않아도 무방하지만 대신 css에서 content:''; 내용값을 채워주셔야합니다.

🔰 css

h1 {
	color: #111;
}
h1 strong {
	position: relative;
    display: inline-block;
}
h1 strong::before,
h1 strong::after {
	content: attr(data-text);
	position: absolute;
	top: 0;
	left: 0;
	display: inline-block;
	width: 0;
	height: 100%;
	overflow: hidden;
	white-space: pre;
    word-break: normal;
	transition: width 1s;
	will-change: width;
}
h1 strong::before {
	color: #fff;
	-webkit-text-fill-color: #fff;
}
h1 strong::after {
	color: red;
	-webkit-text-fill-color: red;
    z-index: 1;
}
h1 strong.fill::before,
h1 strong.fill::after {
	width: 100%
}

❗❗ css 참고사항

  • ::after가 변하는 요소입니다.
  • ::before은 원래 텍스트를 배경색으로 덮는 요소로, color와 -webkit-text-fill-color에 배경색을 넣으면 됩니다. 없어도 무방하며 단지 미적 보완요소일 뿐입니다.
  • data-text를 html에서 안쓰셨다면 여기서 해당 강조부분 텍스트를 적어줘야합니다.

🔰 JS

$(function () {
	setTimeout(function(){
		$("h1 strong").addClass('fill');
	},1000);
});

❗❗ JS 참고사항

  • 페이지가 로딩된 후, 1초 뒤에 클래스 fill을 부여합니다.
profile
이번여름부터 다시 시작한 개발자

0개의 댓글