CSS random() 함수를 활용한 동적 스타일링
개요
CSS random() 함수는 JavaScript 없이 순수 CSS만으로 무작위 값을 생성할 수 있는 새로운 기능이다. 애니메이션 지연, 레이아웃 배치, 색상 생성 등 다양한 용도로 활용 가능하다.
기본 문법
함수 구조
random(min, max, step)
매개변수 설명
- min: 최소값 설정
- max: 최대값 설정
- step: 선택적 매개변수, 증분 단위 지정
- 모든 매개변수는 동일한 단위 타입 사용 필수 (정수, 퍼센트, 길이, 각도 등)
사용 예시
random(0, 100, 2): 0에서 100 사이의 짝수random(0turn, 1turn): 0도에서 360도 사이의 소수값
실제 구현 예제
1. 별 필드 구현
HTML 구조
<html>
<body>
<div class=star></div>
<div class=star></div>
…
<div class=star></div>
</body>
</html>
기본 스타일링
body {
background-color: black;
}
.star {
background-color: white;
border-radius: 50%;
aspect-ratio: 1/1;
width: 3px;
position: fixed;
}
무작위 위치 배치
.star {
background-color: white;
border-radius: 50%;
aspect-ratio: 1/1;
width: 3px;
position: fixed;
top: random(0%, 100%);
left: random(0%, 100%);
}
크기 변화 추가
.star {
background-color: white;
border-radius: 50%;
aspect-ratio: 1/1;
width: random(2px, 10px, 1px);
position: fixed;
top: random(0%, 100%);
left: random(0%, 100%);
}
고급 효과 적용
.star {
--star-size: random(--random-star-size, 1px, 7px, 1px);
background-color: white;
border-radius: 50%;
aspect-ratio: 1/1;
width: var(--star-size);
position: fixed;
top: random(0%, 100%);
left: random(0%, 100%);
filter: drop-shadow(0px 0px calc(var(--star-size) * 0.5) oklch(0.7 0.2 random(0, 100)))
drop-shadow(0px 0px calc(var(--star-size) * 2) white);
mix-blend-mode: hard-light;
}
4각 별 구현
.star.fourpointed {
clip-path: shape(from 50% 0%,line to 50.27% 3.25%, …);
--star-size: random(--random-four-point-size, 20px, 60px, 1px);
rotate: random(element-shared, -45deg, 45deg);
}
2. 그리드 기반 무작위 사각형
.grid {
display: grid;
--rows: 100;
--columns: 100;
grid-template-rows: repeat(var(--rows), 1fr);
grid-template-columns: repeat(var(--columns), 1fr);
width: 100vw;
height: 100vh;
}
.rectangle {
background-color: lch(100% 90% random(0deg, 360deg));
grid-area: random(1, var(--rows), 1) / random(1, var(--columns), 1);
}
3. 사진 스택 효과
.stack img {
width: 100%;
grid-column: 1;
grid-row: 1;
border: 10px solid hsl(0, 100%, 100%);
box-shadow: 10px 10px 40px hsl(0, 0%, 0%, 20%);
--random-rotate: rotate(random(-1 * var(--rotate-offset), var(--rotate-offset)));
transition: .3s ease-out;
transform: var(--random-rotate);
transform-origin: random(0%, 100%) random(0%, 100%);
}
.stack:hover img {
transform: var(--random-rotate) translateX(random(-1 * var(--translate-offset), var(--translate-offset))) translateY(random(-1 * var(--translate-offset), var(--translate-offset)));
}
4. 운명의 바퀴 애니메이션
@keyframes spin {
from {
rotate: 0deg;
}
to {
rotate: 10turn; /* Fallback for browsers that don't support `random()` */
rotate: random(2turn, 10turn, by 20deg);
}
}
무작위 값 공유 방법
최대 무작위성
.random-rect {
width: random(100px, 200px);
height: random(100px, 200px);
}
각 속성과 각 요소가 모두 다른 값을 가짐
요소 내 이름으로 공유
.random-square {
width: random(--foo, 100px, 200px);
height: random(--foo, 100px, 200px);
}
동일한 ident를 사용하여 한 요소 내에서 동일한 값 공유
속성 내 요소 간 공유
.shared-random-rect {
width: random(element-shared, 100px, 200px);
height: random(element-shared, 100px, 200px);
}
element-shared를 사용하여 모든 요소가 동일한 속성값 공유
전역 이름 공유
.shared-random-squares {
width: random(--foo element-shared, 100px, 200px);
height: random(--foo element-shared, 100px, 200px);
}
ident와 element-shared를 함께 사용하여 모든 요소의 모든 속성에서 동일한 값 공유
주요 개념 및 주의사항
사용자 정의 속성과 random()
- 사용자 정의 속성은 텍스트 대체 메커니즘으로 작동
- var() 호출 시 random() 함수가 다시 실행되어 새로운 값 생성
- 동일한 무작위 값 재사용이 필요한 경우 ident 사용 필수
단위 일치 규칙
- min, max, step 매개변수는 모두 동일한 단위 타입 사용 필수
- 퍼센트와 픽셀 등 서로 다른 단위 혼용 불가
브라우저 지원
- 현재 Safari Technology Preview에서 테스트 가능
- CSS Working Group에서 사양 논의 진행 중
- 개발자 피드백을 통한 기능 개선 진행
실용적 활용 팁
성능 최적화
- 과도한 random() 호출은 렌더링 성능에 영향 가능
- 필요한 경우에만 선택적으로 사용
폴백 처리
- random()을 지원하지 않는 브라우저를 위한 대체값 제공
- 기본값 설정 후 random() 덮어쓰기 방식 권장
디버깅
- 무작위 값으로 인한 재현 어려움 고려
- 개발 중에는 고정값으로 테스트 후 random() 적용
참고 자료 및 데모
공식 데모 링크
- 별 필드 예제: https://codepen.io/jdatapple/pen/YPyELeV
- 무작위 사각형: https://codepen.io/ntim/pen/dPYGJxj
- 운명의 바퀴: https://codepen.io/ntim/pen/WbQrMow
피드백 채널
- Jon Davis (Bluesky / Mastodon)
- Jen Simmons (Bluesky / Mastodon)
- Saron Yitbarek (BlueSky)
- WebKit LinkedIn
- WebKit 버그 리포트 시스템