CSS - Advanced
data-* 속성을 css로 불러들이기
ejey
2025. 3. 2. 15:08

오늘
HTML 소스에서 data-* 속성을 적는다.
<h1 data-title="hello">text</h1>
CSS에서 attr() 을 이용하여 불러들일 수 있다.
attr()은 content에서만 사용할 수 있으며, 동적으로 요소의 속성 값을 가져올 수 있음.
h1::after {
content: attr(data-title);
color: red;
font-size: 16px;
}
// 결과 hello
h1::before {
content: "Prefix - " attr(data-title);
font-weight: bold;
color: blue;
}
// 결과 "Prefix - hello"
h1::after {
content: " (" attr(data-title) ")";
font-size: 14px;
color: gray;
}
// 결과 (hello)
attr()의 한계점
주의할 점:
-
- attr()은 color, background, width 등의 속성에서는 사용할 수 없음.
- 예를 들어, 아래 코드는 동작하지 않음. ❌content 속성에서만 사용 가능
h1 { color: attr(data-title); /* 동작하지 않음 */ }
CSS에서 직접 데이터 변경 불가능
- data-* 값은 CSS에서 변경할 수 없으며, JavaScript로만 변경 가능.
반응형