선택자
속성 & 의사 클래스 선택자
CSS3는 강력한 속성 선택자와 의사 클래스(pseudo-class)를 도입했습니다. ^=는 접두사, $=는 접미사, *=는 부분 문자열을 매칭합니다. nth-child를 사용하면 JavaScript 없이도 줄무늬 배경(zebra striping)을 만들 수 있습니다.
/* attribute selectors */
input[type="text"] { border: 1px solid blue; }
a[href^="https"] { color: green; }
a[href$=".pdf"] { color: red; }
a[href*="example"] { font-weight: bold; }
/* pseudo-classes */
a:visited { color: purple; }
li:first-child { font-weight: bold; }
li:nth-child(odd) { background: #f0f0f0; }
input:focus { outline: 2px solid blue; }구조 의사 클래스
구조 의사 클래스는 DOM에서의 위치를 기준으로 요소를 선택합니다. :first-child / :last-child는 양 끝 요소를 지정합니다. nth-child(an+b)는 수식을 지원합니다: 2n은 짝수, 2n+1은 홀수, 3n은 세 번째마다입니다. :nth-of-type은 같은 타입의 형제 요소만 셉니다. :empty는 자식이 없는 요소와 매칭됩니다.
/* positional pseudo-classes */
li:first-child { color: green; }
li:last-child { color: red; }
li:only-child { font-weight: bold; }
/* nth variants */
li:nth-child(3) { color: blue; }
li:nth-child(2n+1) { background: #eee; } /* odd */
li:nth-last-child(2) { color: orange; }
/* type-based */
p:first-of-type { font-size: 1.2em; }
p:nth-of-type(even) { color: gray; }
div:empty { display: none; }:is, :where, :has
:is()와 :where()는 선택자를 묶어 간결하게 쓰게 해줍니다. 차이점은 :is()는 인수 중 가장 높은 명시도(specificity)를 갖는 반면, :where()는 항상 명시도가 0이라는 점입니다 — 오버라이드되기 쉬운 기본 스타일에 이상적입니다. :has()는 오랫동안 기다려 온 부모/관계 선택자로, 자손을 기준으로 요소를 스타일링할 수 있습니다.
/* :is() - matches any selector in the list */
:is(h1, h2, h3) { color: navy; }
:is(.btn, .link):hover { opacity: 0.8; }
/* :where() - same as :is but zero specificity */
:where(article, section) p { line-height: 1.6; }
/* :has() - parent selector (selects element that has a match) */
div:has(> img) { padding: 0; }
card:has(.badge) { border-color: gold; }
form:has(input:invalid) button { opacity: 0.5; }부정 & 폼 의사 클래스
:not()은 선택자를 부정하며, 이제 선택자 목록도 받을 수 있습니다. 폼 의사 클래스(:required, :valid, :invalid, :checked, :placeholder-shown, :in-range)를 사용하면 JavaScript 없이 입력 상태 기반 스타일링이 가능합니다 — 인라인 유효성 피드백이나 커스텀 체크박스/라디오 스타일링에 유용합니다.
/* :not() excludes matching elements */
input:not([type="checkbox"]) { display: block; }
li:not(:last-child) { border-bottom: 1px solid #ddd; }
/* form state pseudo-classes */
input:required { border-color: red; }
input:optional { border-color: #ccc; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
input:in-range { color: black; }
input:out-of-range { color: red; }
input:placeholder-shown { background: #fafafa; }
input:checked + label { font-weight: bold; }명시도 & 캐스케이드
명시도(specificity)는 선택자가 충돌할 때 어떤 규칙이 적용될지 결정합니다. ID, 클래스, 요소 수를 (a,b,c)로 셉니다. !important는 캐스케이드를 무시하지만 유지보수성을 해치므로 피해야 합니다. 명시도가 같으면 소스 순서상 나중에 온 규칙이 이깁니다. DevTools에서 계산된 캐스케이드를 확인할 수 있습니다.
/* specificity ranking: inline > ID > class/attr/pseudo > type/element */
#nav .item { color: red; } /* 1,1,0 */
.menu .item { color: blue; } /* 0,2,0 */
li.item { color: green; } /* 0,1,1 */
/* !important overrides normal declarations */
.btn { color: white !important; }
/* source order wins on equal specificity */
.late { color: purple; } /* wins over .early */박스 모델
box-sizing
box-sizing: border-box는 padding과 border를 선언된 width/height 안에 포함시켜 크기 계산을 예측 가능하게 만듭니다. content-box(기본값)는 이를 그 위에 더합니다. 전역으로 border-box를 적용하는 것이 가장 중요한 CSS 리셋입니다 — 가장 흔한 레이아웃 계산의 골칫거리를 없애 줍니다.
/* default: width = content only */
.box-content { box-sizing: content-box; width: 200px; padding: 20px; } /* total 240px */
/* padding & border inside width */
.box-border { box-sizing: border-box; width: 200px; padding: 20px; border: 2px solid; } /* total 200px */
/* universal reset - apply everywhere */
*, *::before, *::after {
box-sizing: border-box;
}마진 & 패딩
padding은 테두리 안쪽(배경을 상속)이고, margin은 바깥쪽(투명)입니다. 인접한 블록 요소 사이의 수직 마진은 더 큰 값으로 병합(collapse)되지만, 수평 마진은 절대 병합되지 않습니다. margin: 0 auto는 너비가 정해진 블록 요소를 가운데 정렬합니다. 음수 마진은 콘텐츠를 당길 수 있지만 아껴서 사용하세요.
.box {
/* top right bottom left (clockwise) */
margin: 10px 20px 15px 25px;
/* 2 values: vertical horizontal */
padding: 10px 20px;
/* single value: all sides */
margin: 0 auto; /* horizontal centering for fixed-width block */
}
/* margin collapse (vertical only) */
.a { margin-bottom: 30px; }
.b { margin-top: 20px; }
/* gap between .a and .b = 30px, not 50px (collapsed to larger) */
/* negative margins pull elements together */
.pull-left { margin-left: -10px; }box-shadow
box-shadow 문법: offset-x offset-y blur-radius spread-radius color. 양수 오프셋은 그림자를 오른쪽/아래로 밉니다. inset은 안쪽 그림자를 만듭니다. 여러 그림자를 겹칠 수 있으며 첫 번째가 가장 위에 옵니다. 반투명하고 자연스러운 그림자에는 rgba를 사용하세요. 블러가 0인 하드 섀도는 플랫하고 강한 느낌을 줍니다.
/* offset-x offset-y blur spread color */
.card { box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
/* inset shadow (inside the box) */
.inset { box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }
/* multiple shadows (first = top layer) */
.layered { box-shadow: 0 1px 2px #000, 0 8px 24px rgba(0,0,0,0.15); }
/* no blur, hard shadow (neo-brutalism) */
.hard { box-shadow: 6px 6px 0 #000; }
/* glow effect */
.glow { box-shadow: 0 0 20px rgba(0,150,255,0.6); }디스플레이 타입
display: none은 요소를 레이아웃에 서 제거합니다(공간도 차지하지 않음). block 요소는 전체 너비를 차지하며 세로로 쌓이고, inline 요소는 텍스트처럼 흐르며 width/height를 무시합니다. inline-block은 인라인 흐름과 블록 크기 지정을 결합합니다. flow-root는 clearfix 핵 없이 float를 해제합니다. contents는 자식은 레이아웃에 유지한 채 박스 자체를 사라지게 합니다.
/* block: full width, new line */
div, p { display: block; }
/* inline: flows with text, ignores width/height */
span, a { display: inline; }
/* inline-block: flows inline but accepts width/height */
.tag { display: inline-block; width: 100px; }
/* none: removed from layout entirely */
.hidden { display: none; }
/* modern display values */
.flow { display: flow-root; } /* new block formatting context */
.contents { display: contents; } /* element's box disappears, children participate */오버플로우(Overflow)
overflow는 박스를 넘는 콘텐츠의 처리 방식을 제어합니다. visible(기본값)은 그대로 넘치게 두고, hidden은 잘라내고, auto는 필요할 때만 스크롤바를 추가하며, scroll은 항상 보여줍니다. clip(신규)은 hidden과 비슷하지만 JS로도 스크롤할 수 없습니다. overflow-y/x로 축을 독립적으로 제어하세요. overflow를 visible 외의 값으로 설정하면 새로운 포매팅 컨텍스트가 생성됩니다.
.scrollable {
overflow: auto; /* scrollbars when needed */
overflow-y: scroll; /* always show vertical scrollbar */
overflow-x: hidden; /* hide horizontal overflow */
}
/* visible (default) - content spills out */
.spill { overflow: visible; }
/* clip - like hidden but no programmatic scroll */
.clipped { overflow: clip; }
/* clip to a shape */
.custom-clip {
overflow: clip;
overflow-clip-margin: 20px;
}
/* longhand for both axes */
.both { overflow-x: hidden; overflow-y: auto; }Flexbox
플렉스 컨테이너
display: flex는 요소를 플렉스 컨테이너로 만듭니다. justify-content는 주축(행에서는 가로)을 따라 아이템을 정렬하고, align-items는 교차축을 따라 정렬합니다. flex-wrap은 아이템이 새 줄로 감기게 합니다. gap은 마진 기반 간격 핵을 대체합니다. Flexbox는 1차원 레이아웃(행 또는 열)에 탁월합니다.
.container {
display: flex;
flex-direction: row; /* row | row-reverse | column | column-reverse */
justify-content: center; /* main axis: flex-start | center | space-between | space-around | space-evenly */
align-items: center; /* cross axis: stretch | flex-start | center | baseline */
flex-wrap: wrap; /* nowrap | wrap | wrap-reverse */
gap: 16px; /* spacing between items */
align-content: space-between; /* multi-line spacing */
}플렉스 아이템
flex-grow는 아이템이 남은 공간을 채우기 위해 늘어나는 정도를 제어합니다(1 = 균등 비율). flex-shrink는 줄어드는 정도를, flex-basis는 초기 크기를 제어합니다. flex: 1 축약형은 0 기준에서 균등하게 늘어난다는 뜻으로, 균등한 열에 딱 맞습니다. align-self는 한 아이템만 컨테이너의 align-items를 덮어씁니다. order는 DOM 순서를 바꾸지 않고 시각적 순서만 변경합니다.
.item {
flex-grow: 1; /* grow to fill extra space (0 = don't grow) */
flex-shrink: 1; /* shrink when space is tight (0 = don't shrink) */
flex-basis: 200px; /* initial size before growing/shrinking */
/* shorthand: flex: grow shrink basis */
flex: 1 1 200px; /* flexible from 200px */
flex: 1; /* = 1 1 0% - equal distribution */
flex: 0 0 250px; /* fixed width, no grow/shrink */
align-self: flex-end; /* override align-items for this item */
order: 2; /* visual reordering (default 0) */
}플렉스 정렬 패턴
Flexbox는 가운데 정렬을 아주 쉽게 만듭니다: justify-content: center + align-items: center. 스티키 푸터는 세로 플렉스 body에 min-height: 100vh를 주고 메인 콘텐츠에 flex: 1을 설정하면 됩니다. 내비게이션 바에서는 space-between이 첫/마지막 아이템을 양 끝으로 밀어냅니다. auto 마진(margin-left: auto)은 아이템을 밀어내는 justify-content의 유연한 대안입니다.
/* perfect centering */
.center {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* sticky footer: body is flex column */
body { display: flex; flex-direction: column; min-height: 100vh; }
main { flex: 1; } /* grows to fill, pushing footer down */
/* navbar: space between */
.nav { display: flex; justify-content: space-between; }
/* auto margins absorb space */
.push-right { margin-left: auto; }플렉스 랩 & 반응형 그리드
flex-wrap: wrap은 공간이 부족할 때 아이템을 새 줄로 흐 르게 합니다. flex: 1 1 280px은 280px에서 시작해 행을 채우도록 늘어나는 카드를 만듭니다. 미디어 쿼리 없이 반응형 카드 그리드가 가능합니다. 주의: 마지막 행의 아이템들이 늘어나 균일하지 않아 보일 수 있습니다 — 일관된 카드 그리드에는 CSS Grid가 더 나은 선택일 때가 많습니다.
.cards {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
/* start at 280px, grow & shrink fluidly */
flex: 1 1 280px;
/* prevent stretching beyond readable width */
max-width: 100%;
}
/* OR fixed-width cards that wrap */
.card-fixed {
flex: 0 0 300px;
}
/* last row items stretch to fill - to avoid, use grid instead */
/* gap wraps with items automatically */플렉스 방향 & 축
flex-direction이 주축을 결정합니다. row(기본값)에서는 justify-content가 가로 정렬을, column에서는 세로 정렬을 제어합니다 — 축이 바뀝니다. 정렬할 때는 항상 '주축이 무엇인가?'를 물으세요. row-reverse와 column-reverse는 아이템 순서를 뒤집으며, justify-content가 공간을 분배하는 방식에도 영향을 줍니다.
/* row: main axis = horizontal */
.row { display: flex; flex-direction: row; justify-content: center; }
/* column: main axis = vertical (axes swap!) */
.col { display: flex; flex-direction: column; align-items: center; }
/* reverse order */
.reverse { display: flex; flex-direction: row-reverse; }
/* centering in column: justify-content centers vertically */
.col-center {
display: flex;
flex-direction: column;
justify-content: center; /* vertical center */
align-items: center; /* horizontal center */
}그리드 레이아웃
그리드 컨테이너
display: grid는 2차원 레이아웃을 만듭니다. grid-template-columns는 열 트랙을 정의하고, fr 단위는 남은 공간을 비율대로 분배합니다. repeat(auto-fit, minmax(200px, 1fr))은 반응형 그리드의 마법 같은 조합입니다 — 미디어 쿼리 없이 열이 자동 생성·조절됩니다. gap은 트랙 사이 간격을 깔끔하게 추가합니다.
.grid {
display: grid;
/* fixed columns */
grid-template-columns: 200px 1fr 200px;
/* responsive auto columns */
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: auto 1fr auto;
gap: 20px; /* row + column gap */
row-gap: 20px; /* gap between rows */
column-gap: 16px; /* gap between columns */
}그리드 템플릿 영역
grid-template-areas는 이름 붙은 영역으로 레이아웃을 시각적으로 그릴 수 있게 해 줍니다 — 가독성이 매우 높습니다. 각 따옴표 문자열이 한 행이고, 이름이 아이템을 배치하며, 점(.)은 빈 셀을 표시합니다. grid-area: name을 가진 아이템이 해당 영역을 채웁니다. 앱 셸 같은 페이지 단위 레이아웃을 만드는 가장 명확한 방법입니다.
.layout {
display: grid;
grid-template-columns: 200px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
min-height: 100vh;
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
/* empty cell with a dot */
grid-template-areas: "header header" "sidebar .";그리드 아이템 배치
그리드 아이템은 라인 번호로 명시적 배치가 가능합니다. grid-column: 1 / 3은 1번 라인부터 3번 라인까지(2개 열) 차지합니다. span 키워드는 트랙 개수로 크기를 정합니다. grid-template-columns에서 라인에 이름을 붙일 수도 있어 가독성이 좋아집니다. 명시적 배치가 없으면 아이템은 빈 셀에 자동 배치(auto-flow)됩니다.
.item {
/* place by line numbers: row-start / col-start / row-end / col-end */
grid-column: 1 / 3; /* span columns 1 to 3 */
grid-row: 1 / 2;
/* span keyword */
grid-column: span 2; /* span 2 columns */
grid-row: 2 / span 3;
/* shorthand: grid-area: row-start / col-start / row-end / col-end */
grid-area: 1 / 1 / 3 / 4;
/* name a line and reference it */
grid-column-start: content-start;
}그리드 정렬
그리드 정렬은 두 수준에서 동작합니다. justify-content/align-content는 남는 공간이 있을 때 그리드 전체를 컨테이너 안에 배치합니다. justify-items/align-items는 셀 안에서 아이템을 정렬합니다(기본값 stretch). justify-self/align-self는 아이템별로 정렬을 덮어씁니다. 'justify' = 인라인/주축, 'align' = 블록/교차축입니다.
.grid {
display: grid;
grid-template-columns: repeat(3, 100px);
/* align tracks within container */
justify-content: center; /* center the grid horizontally */
align-content: center; /* center vertically (needs fixed height) */
/* align items within their cells */
justify-items: stretch; /* fill cell width (default) */
align-items: center; /* center within cell height */
}
.item {
justify-self: start; /* override justify-items for one item */
align-self: end;
}auto-fit vs auto-fill
둘 다 맞는 만큼 트랙을 만들지만, 아이템이 적을 때는 다르게 동작합니다. auto-fit은 빈 트랙을 접어서 기존 아이템이 행을 채우도록 늘립니다. auto-fill은 빈 트랙을 유지하므로 아이템이 최소 크기를 유지합니다. 아이템을 키워 공간을 채우고 싶으면 auto-fit, 고정적·균일한 크기를 원하면 auto-fill을 사용하세요.
/* auto-fit: empty tracks collapse, items stretch to fill */
.autofit {
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}
/* auto-fill: empty tracks remain, items keep their size */
.autofill {
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
}
/* with few items:
auto-fit -> items stretch to fill the row
auto-fill -> items stay small, leaving empty columns */위치 지정
position 값
static이 기본값입니다. relative는 일반 흐름 위치에서 오프셋합니다(공간은 유지됨). absolute는 흐름에서 제거되고, 가장 가까운 position 지정 조상(또는 뷰포트)을 기준으로 배치됩니다. fixed는 브라우저 뷰포트 기준입니다. sticky는 스크롤 위치에 따라 relative와 fixed 사이를 전환합니다 — 스티키 헤더에 이상적입니다.
/* static - default, flows normally */
.static { position: static; }
/* relative - offset from its normal position */
.relative { position: relative; top: 10px; left: 20px; }
/* absolute - positioned relative to nearest positioned ancestor */
.absolute { position: absolute; top: 0; right: 0; }
/* fixed - positioned relative to viewport (stays on scroll) */
.fixed { position: fixed; bottom: 0; left: 0; }
/* sticky - relative until scroll threshold, then fixed */
.sticky { position: sticky; top: 0; }절대 가운데 정렬
절대 가운데 정렬 방법은 여럿입니다. translate(-50%, -50%) 트릭은 크기와 무관하게 동작합니다. inset: 0 + margin: auto 기법은 명시적 크기가 필요합니다. 현대적인 방법은 display: grid에 place-items: center(align-items + justify-items의 축약)를 쓰는 것입니다 — 위치 계산이 필요 없는 가장 간단한 방법입니다.
/* classic: position absolute + transform */
.center {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
/* inset: 0 + margin: auto (needs width/height) */
.center-auto {
position: absolute;
inset: 0; /* top/right/bottom/left: 0 */
margin: auto;
width: 300px;
height: 200px;
}
/* modern: no positioning needed */
.center-grid { display: grid; place-items: center; }스티키 포지셔닝
position: sticky는 임계값(예: top: 0)에 도달할 때까지 일반 흐름에 있다가, 이후 fixed처럼 붙어 있습니다. 스티키 헤더나 목차 사이드바에 완벽합니다. 주의: 스크롤 방향의 조상에 overflow: hidden/auto/scroll이 있으면 그 요소가 컨테이닝 블록이 되어 기대 동작이 깨집니다. sticky 요소에는 항상 배경과 z-index를 설정하세요.
.header {
position: sticky;
top: 0; /* sticks when header hits top of viewport */
z-index: 100;
background: white;
}
/* sticky sidebar that scrolls with content until threshold */
.sidebar {
position: sticky;
top: 60px; /* offset below the fixed header */
max-height: calc(100vh - 60px);
overflow-y: auto;
}
/* NOTE: a parent with overflow: hidden breaks sticky */z-index & 쌓임 컨텍스트
z-index는 positioned(비 static) 요소에서만 동작합니다. 쌓임 컨텍스트(stacking context)는 position + z-index 외에도 opacity < 1, transform, filter, will-change, isolation: isolate로 생성됩니다. 쌓임 컨텍스트 안에서는 자식 z-index가 격리됩니다 — 자식은 조상의 형제보다 위에 렌더링될 수 없습니다. 이를 이해하면 z-index 무한 경쟁을 막을 수 있습니다.
.modal { position: fixed; z-index: 1000; }
.overlay { position: fixed; z-index: 999; }
.card { position: relative; z-index: 1; }
/* creating a stacking context (isolates z-index) */
.context {
position: relative;
z-index: 0; /* children's z-index only matters within this */
}
/* other properties that create stacking contexts:
opacity < 1, transform, filter, will-change, isolation: isolate */
.isolated { isolation: isolate; }inset 축약형
inset은 top, right, bottom, left의 논리적 축약형입니다 — margin/padding처럼 1, 2, 4개의 값을 받습니다. inset: 0은 절대 위치 요소를 컨테이닝 블록을 채우도록 늘립니다. 네 속성을 각각 선언하는 것보다 깔끔하며, margin: auto와 함께 쓰면 가운데 정렬도 됩니다.
/* inset sets top right bottom left (like margin) */
.popup {
position: absolute;
inset: 0; /* all sides = 0 (stretches to fill parent) */
}
/* two values: vertical horizontal */
.pill {
position: absolute;
inset: 10px 20px; /* top/bottom 10px, left/right 20px */
}
/* four values: top right bottom left */
.box {
position: absolute;
inset: 10px 20px 30px 40px;
}
/* longhand equivalents */
.inset-longhand {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
}텍스트 스타일링
폰트 속성
font-family는 항상 일반 계열(serif, sans-serif, monospace)로 끝나야 합니다 — 최후의 폴백입니다. font-weight는 100~900이며, 일반적으로 400 normal, 700 bold를 씁니다. line-height는 단위 없이(1.5) 설정하는 것이 좋습니다 — font-size에 맞춰 같이 커집니다. font 축약형에는 size와 family가 필수이며, 순서는 style weight size/line-height family입니다.
body {
font-family: "Helvetica Neue", Arial, sans-serif; /* fallback chain */
font-size: 16px;
font-weight: 400; /* 100-900; 400=normal, 700=bold */
font-style: italic; /* normal | italic | oblique */
line-height: 1.5; /* unitless = multiplier of font-size */
letter-spacing: 0.5px;
word-spacing: 2px;
font-variant: small-caps;
}
/* shorthand: style weight size/line-height family (order matters) */
p { font: italic 700 16px/1.5 "Georgia", serif; }텍스트 포매팅
text-align: justify는 빈 공간의 강(river)을 만들 수 있으니 hyphens: auto와 함께 쓰면 더 깔끔합니다. text-decoration은 이제 line, style, color를 하나의 축약형으로 받습니다. text-transform: capitalize는 각 단어의 첫 글자를 대문자로 만듭니다. white-space: nowrap은 줄바꿈을 막습니다. text-shadow는 offset-x offset-y blur color를 받습니다.
.text {
text-align: justify; /* left | right | center | justify */
text-decoration: underline wavy red; /* line style color */
text-decoration: line-through;
text-transform: uppercase; /* lowercase | capitalize */
text-indent: 2em; /* first-line indent */
white-space: nowrap; /* prevent wrapping */
word-break: break-word; /* break long words */
hyphens: auto; /* auto-hyphenate (needs lang attr) */
text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
}텍스트 오버플로우 & 말줄임표
한 줄 잘라내기에는 세 속성이 필요합니다: white-space: nowrap, overflow: hidden, text-overflow: ellipsis. 여러 줄 잘라내기에는 display: -webkit-box와 함께 -webkit-line-clamp를 사용합니다(여전히 -webkit- 접두사가 필요하지만 모든 모던 브라우저에서 동작합니다). 잘라내기가 발동하려면 max-width 또는 width가 필요합니다.
.truncate {
/* three properties required for ellipsis */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis; /* clip | ellipsis */
max-width: 200px;
}
/* multi-line clamp (line-clamp) */
.clamp {
display: -webkit-box;
-webkit-line-clamp: 3; /* limit to 3 lines */
-webkit-box-orient: vertical;
overflow: hidden;
}
/* custom fade effect */
.fade {
-webkit-mask-image: linear-gradient(to bottom, black 70%, transparent);
}text-shadow & 효과
text-shadow는 offset-x offset-y blur-radius color를 받습니다. 여러 그림자를 겹칠 수 있고 첫 번째가 가장 위에 옵니다 — 네온 발광이나 텍스트 외곽선에 유용합니다(4방향 그림자가 외곽선을 흉내 냅니다). -webkit-text-stroke와 달리 text-shadow는 모든 브라우저에서 지원됩니다. 블러 없는 하드 섀도는 레트로 감성의 스티커 느낌을 줍니다.
/* x-offset y-offset blur color */
.shadow { text-shadow: 2px 2px 4px rgba(0,0,0,0.3); }
/* multiple shadows (first = top) */
.neon { text-shadow: 0 0 10px #fff, 0 0 20px #fff, 0 0 30px #0ff; }
/* 3D letterpress effect */
.letterpress { text-shadow: 0 1px 0 rgba(255,255,255,0.5); }
/* outline text (no blur, light color) */
.outline { text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000; }
/* hard shadow retro effect */
.retro { text-shadow: 4px 4px 0 #ff6b6b; }쓰기 방향 & 방향성
writing-mode는 텍스트 방향을 제어합니다: horizontal-tb(기본값), vertical-rl(예: 한자/일본어 전통 표기), vertical-lr. direction: rtl은 아랍어 같은 오른쪽에서 왼쪽으로 쓰는 언어를 처리합니다. 논리 속성(margin-inline-start, padding-block, inset-inline-end)은 쓰기 방향과 direction에 맞춰 자동으로 적응합니다 — 진정한 국제화와 방향 독립적 레이아웃에 필수입니다.
/* horizontal (default) */
.horizontal { writing-mode: horizontal-tb; }
/* vertical, top to bottom */
.vertical-rl { writing-mode: vertical-rl; }
.vertical-lr { writing-mode: vertical-lr; }
/* text direction */
.rtl { direction: rtl; unicode-bidi: bidi-override; }
/* logical properties adapt to writing mode */
.box {
margin-inline-start: 10px; /* logical left in LTR */
padding-block: 20px; /* logical top/bottom */
inset-inline-end: 0; /* logical right in LTR */
}배경 & 그라디언트
배경 축약형
background 축약형은 모든 배경 속성을 받습니다. position과 size를 함께 쓸 때는 슬래시로 구분합니다(center/cover). 여러 배경은 쉼표로 겹치며, 먼저 선언된 것이 가장 위에 옵니다. 단색 배경은 폴백용으로 항상 마지막에 쓰세요. 박스를 채우려면 cover, 이미지 전체가 보이려면 contain을 사용합니다.
.box {
/* longhand */
background-color: #fff;
background-image: url("bg.png");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-attachment: fixed;
/* shorthand (color image position/size repeat attachment) */
background: #fff url("bg.png") center/cover no-repeat fixed;
}
/* multiple backgrounds (first = top layer) */
.multi {
background: url("top.png") top left/contain no-repeat,
url("bottom.png") bottom right/cover no-repeat #eee;
}선형 그라디언트
linear-gradient(direction, color-stops)는 부드러운 전환을 만듭니다. 방향은 키워드(to right)나 각도(45deg)가 될 수 있습니다. 색상 정지점(stop)에 퍼센트 위치를 넣을 수 있으며, 같은 위치에 두 정지점을 놓으면 경계가 생깁니다(스트라이프에 좋습니다). 그라디언트는 이미지이므로 background-image에 넣고, 이미지가 허용되는 곳이라면 어디든 쓸 수 있습니다.
/* direction or angle, then color stops */
.gradient { background: linear-gradient(to right, red, blue); }
.gradient-45 { background: linear-gradient(45deg, red, blue); }
/* multiple color stops */
.rainbow { background: linear-gradient(to right, red, orange, yellow, green, blue); }
/* color stops with positions */
.hard-stop { background: linear-gradient(to right, red 0%, red 50%, blue 50%, blue 100%); }
/* transparent stops for fade effects */
.fade { background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent); }원형 & 원뿔형 그라디언트
radial-gradient는 중심점에서 바깥으로 퍼집니다 — 스포트라이트와 버튼에 유용합니다. 중심 위치(at top left)와 모양/크기(circle, closest-side)를 지정할 수 있습니다. conic-gradient는 한 점 주위로 색을 회전합니다 — 파이 차트와 색상환에 완벽합니다. conic 그라디언트의 하드 스탑은 깔끔한 파이 조각을 만듭니다.
/* radial: radiates from a center point */
.radial { background: radial-gradient(circle, red, blue); }
.radial-c { background: radial-gradient(circle at top left, #fff, #000); }
.radial-size { background: radial-gradient(closest-side, red, blue); }
/* conic: rotates around a center point */
.pie { background: conic-gradient(red 0% 30%, blue 30% 70%, green 70% 100%); }
/* conic with angle start */
.spin { background: conic-gradient(from 45deg, red, yellow, green, red); }background-clip & origin
background-clip은 배경이 어디까지 확장되는지 제어합니다: border-box(기본값, 테두리 아래까지), padding-box(테두리 안), content-box(padding 안). 헤드라인 트릭: background-clip: text와 color: transparent로 텍스트를 그라디언트나 이미지로 채웁니다. Safari를 위해 -webkit- 접두사 버전을 항상 포함하세요. background-origin은 배경의 위치 기준 영역을 설정합니다.
/* clip: where the background paints */
.border-box { background-clip: border-box; } /* default - under border */
.padding-box { background-clip: padding-box; } /* inside border */
.content-box { background-clip: content-box; } /* inside padding */
/* text clip: gradient-filled text */
.gradient-text {
background: linear-gradient(to right, red, blue);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
-webkit-text-fill-color: transparent;
}
/* origin: where positioning starts */
.origin { background-origin: content-box; }배경 고정 & 패럴랙스
background-attachment: fixed는 패럴랙스 효과를 만듭니다 — 콘텐츠가 그 위로 스크롤되는 동안 배경이 고정됩니다. scroll(기본값)은 요소와 함께 움직이고, local은 요소의 콘텐츠와 함께 움직입니다(스크롤 박스에 유용). fixed attachment는 모바일에서 버벅이고 지원이 좋지 않으므로, 프로덕션 패럴랙스에는 스크롤 위치 기반 transform: translate3d를 사용하세요.
/* fixed: background stays put during scroll (parallax) */
.parallax {
background-image: url("hero.jpg");
background-attachment: fixed;
background-size: cover;
height: 100vh;
}
/* scroll: scrolls with element (default) */
.scroll { background-attachment: scroll; }
/* local: scrolls with element's content */
.local {
background-attachment: local; /* scrolls with inner content */
}
/* NOTE: background-attachment: fixed has poor mobile support
prefer transform-based parallax for mobile */테두리 & 둥근 모서리
border-radius
border-radius는 모서리를 둥글게 하며 1~4개의 값을 받습니다(왼쪽 위부터 시계 방향). 슬래시는 타원 모서리를 위한 가로/세로 반지름을 구분합니다. 정사각형에 border-radius: 50%를 주면 완벽한 원, 직사각형에는 타원이 됩니다. 개별 속성(border-top-left-radius)으로 모서리별 제어가 가능합니다. 둥근 모서리는 배경, 테두리, (overflow: hidden이면) 자식 콘텐츠까지 잘라냅니다.
.box { border-radius: 10px; } /* all corners */
.box-2 { border-radius: 10px 20px; } /* top-left/bottom-right top-right/bottom-left */
.box-4 { border-radius: 10px 20px 30px 40px; } /* TL TR BR BL (clockwise) */
/* per-corner longhand */
.card {
border-top-left-radius: 10px;
border-top-right-radius: 20px;
border-bottom-right-radius: 30px;
border-bottom-left-radius: 40px;
}
/* elliptical corners (horizontal / vertical) */
.ellipse { border-radius: 50px / 25px; }
/* perfect circle (square element) */
.circle { border-radius: 50%; }border-image
border-image는 이미지를 9개 영역으로 나눠 모서리/가장자리를 테두리에 적용합니다. border-image-slice가 원본 이미지를 나누고, repeat는 가장자리 타일링 방식을 제어합니다. 흔한 현대 트릭: linear-gradient와 slice 1로 border-image를 쓰면 그라디언트 테두리가 됩니다. 참고: border-image는 border-style을 대체하므로 border-width를 먼저 설정하세요.
.frame {
border: 20px solid transparent;
border-image-source: url("frame.png");
border-image-slice: 30; /* slice image into 9 regions */
border-image-width: 20px;
border-image-outset: 0;
border-image-repeat: stretch; /* stretch | repeat | round | space */
}
/* shorthand */
.frame-shorthand {
border: 20px solid transparent;
border-image: url("frame.png") 30 stretch;
}
/* gradient border (using border-image) */
.grad-border {
border: 4px solid;
border-image: linear-gradient(to right, red, blue) 1;
}다중 테두리
CSS는 border 속성을 여러 겹 쌓을 수 없지만 우회법이 있습니다. 오프셋 0인 box-shadow와 spread 값으로 선명한 바깥 테두리를 만들 수 있습니다(border-radius와 호환). outline은 바깥에 두 번째 테두리를 그리지만 border-radius를 무시합니다. 의사 요소는 반지름까지 완전한 제어를 제공합니다. 기법마다 트레이드오프가 있으니 둥근 모서리 필요 여부로 선택하세요.
/* technique 1: box-shadow (no rounded issue) */
.multi-shadow {
box-shadow: 0 0 0 5px red, 0 0 0 10px blue;
}
/* technique 2: outline (outside border, no radius) */
.outline-border {
border: 5px solid red;
outline: 5px solid blue;
outline-offset: 0;
}
/* technique 3: pseudo-element (full control) */
.pseudo-border {
position: relative;
border: 5px solid red;
}
.pseudo-border::after {
content: "";
position: absolute;
inset: -10px;
border: 5px solid blue;
border-radius: inherit;
}그라디언트 테두리
border-image는 border-radius를 지원하지 않아 그라디언트 테두리는 까다롭습니다. 견고한 해법: 두 배경을 겹치는 것입니다 — padding-box로 잘라낸 단색과 border-box로 잘라낸 그라디언트, 그리고 투명한 border. border-radius를 존중하며 모든 곳에서 동작합니다. 둥근 모서리가 필요 없다면 더 간단한 border-image 방식으로 충분합니다.
/* method 1: border-image (works but no border-radius) */
.grad-1 {
border: 4px solid;
border-image: linear-gradient(to right, red, blue) 1;
}
/* method 2: background-clip trick (works with radius) */
.grad-2 {
border: 4px solid transparent;
border-radius: 12px;
background:
linear-gradient(white, white) padding-box,
linear-gradient(to right, red, blue) border-box;
}
/* method 3: mask + pseudo (advanced, supports radius + animation) */아웃라인 & 포커스 스타일
outline은 테두리 바깥에 그려지고 레이아웃에 영향을 주지 않아 포커스 표시기에 이상적입니다. outline-offset은 간격을 추가합니다. 중요한 접근성 규칙: 눈에 보이는 대체물 없이 outline: none을 설정하지 마세요. :focus-visible은 키보드 탐색에서만(마우스 클릭은 제외) 아웃라인을 보여줍니다 — 포커스 스타일링의 현대적이고 사용자 친화적인 방법입니다.
/* outline: doesn't affect layout, draws outside border */
.focusable:focus {
outline: 2px solid blue;
outline-offset: 2px; /* gap between element and outline */
}
/* never use outline: none without a replacement */
button:focus { outline: none; box-shadow: 0 0 0 3px rgba(0,150,255,0.5); }
/* :focus-visible: only shows outline for keyboard users */
button:focus-visible { outline: 2px solid blue; outline-offset: 2px; }
button:focus:not(:focus-visible) { outline: none; }
/* outline shorthand */
.box { outline: 2px dashed red; }트랜스폼
2D 트랜스폼
2D 트랜스폼 — translate, rotate, scale, skew — 는 형제 요소를 리플로우시키지 않고 요소를 이동·왜곡합니다. 트랜스폼을 조합하면 오른쪽에서 왼쪽으로 적용되므로 순서가 중요합니다: rotate 다음 translate는 회전된 축을 따라 이동합니다. 트랜스폼은 리플로우를 유발하지 않아 애니메이션에 이상적이며 GPU 가속됩니다.
.box { transform: translate(50px, 20px); } /* move right 50, down 20 */
.box-x { transform: translateX(50px); }
.box-scale { transform: scale(1.5); } /* grow 1.5x */
.box-scale-2 { transform: scale(1, 2); } /* x 1, y 2 */
.box-rotate { transform: rotate(45deg); } /* clockwise */
.box-skew { transform: skew(20deg, 10deg); } /* skew x, y */
/* combine transforms (order matters!) */
.combo { transform: translate(20px, 0) rotate(45deg) scale(1.2); }
/* transform does NOT affect layout (no reflow) */transform-origin
transform-origin은 트랜스폼의 기준점을 설정합니다 — 기본값은 요소의 중심입니다. 키워드(top left), 픽셀, 퍼센트를 받습니다. 기준점을 바꾸면 회전과 스케일 동작이 크게 달라집니다: 카드가 윗면을 축으로 뒤집히려면 transform-origin: top이 필요합니다. 3D 트랜스폼에서는 z축 값도 지정할 수 있습니다.
.box { transform: rotate(45deg); }
/* default origin: center center (50% 50%) */
.center { transform-origin: center center; }
/* rotate around top-left corner */
.tl { transform-origin: top left; transform: rotate(45deg); }
/* custom point (x y) */
.custom { transform-origin: 20px 50px; transform: rotate(45deg); }
/* 3-value form (x y z) */
.three-d { transform-origin: 0 0 100px; }
/* percentage-based */
.pct { transform-origin: 100% 0; } /* top-right corner */3D 트랜스폼
3D 트랜스폼은 rotateX, rotateY, rotateZ, translateZ, scaleZ를 추가합니다. 깊이를 사용하려면 perspective(n)를 첫 번째 변환 함수로(또는 부모에) 적용해야 합니다 — 값이 작을수록 3D 효과가 과장됩니다. translate3d와 scale3d는 GPU 가속되어 2D 대응물보다 애니메이션 성능이 좋습니다.
.card { transform: perspective(1000px) rotateY(45deg); }
/* rotateX/Y/Z - rotate around 3D axes */
.flip { transform: rotateX(180deg); } /* flip horizontally */
.turn { transform: rotateY(180deg); } /* flip like a page */
.spin { transform: rotateZ(90deg); } /* same as rotate() */
/* translate3d (GPU-accelerated) */
.move { transform: translate3d(50px, 20px, 100px); }
/* scale3d */
.grow { transform: scale3d(1.5, 1.5, 1.5); }
/* combined 3D */
.combo-3d { transform: perspective(800px) rotateX(15deg) rotateY(-20deg) translateZ(-50px); }원근감 & 3D 공간
perspective는 관찰자의 거리를 정의합니다 — 작을수록 3D가 더 극적입니다. 부모에 두면 모든 자식이 같은 소실점을 공유합니다. transform-style: preserve-3d는 중첩 요소가 하나의 3D 공간에 존재하게 합니다(큐브 만들기에 필수). backface-visibility: hidden은 요소의 뒷면을 숨깁니다 — 카드 뒤집기 효과의 핵심입니다.
/* perspective on parent: applies to all children uniformly */
.scene { perspective: 1000px; }
.cube { transform: rotateY(45deg); }
/* perspective() in transform: only affects that element */
.solo { transform: perspective(1000px) rotateY(45deg); }
/* perspective-origin: vanishing point */
.scene { perspective: 1000px; perspective-origin: top left; }
/* transform-style: preserve-3d lets children share 3D space */
.cube {
transform-style: preserve-3d;
transform: rotateY(30deg);
}
.cube .face { position: absolute; transform: translateZ(50px); }
/* backface-visibility: hide back of flipped element */
.card { backface-visibility: hidden; }트랜스폼 애니메이션 (성능)
항상 transform과 opacity를 애니메이션하세요 — GPU 가속되며 레이아웃(리플로우)과 페인트를 유발하지 않습니다. top/left/width/margin을 애니메이션하면 매 프레임 레이아웃 재계산이 일어나 버벅임이 생깁니다. will-change: transform은 브라우저에 컴포지터 레이어를 미리 준비하라고 힌트하지만, 남용하면 메모리를 낭비합니다. 애니메이션 직전에 적용하고 끝나면 제거하세요.
/* GOOD: animate transform & opacity (GPU-accelerated) */
.smooth {
transition: transform 0.3s ease;
}
.smooth:hover { transform: translateY(-5px); }
/* BAD: animating top/left triggers reflow */
.janky { transition: top 0.3s; }
.janky:hover { top: -5px; }
/* will-change: hint the browser to optimize */
.prepared {
will-change: transform; /* prepare for upcoming transform changes */
}
/* force GPU layer (use sparingly) */
.gpu { transform: translateZ(0); }트랜지션
트랜지션 축약형
transition: property duration timing-function delay. 기본값은 all 0s ease 0s입니다 — 그래서 transition: 0.3s만 써도 변하는 모든 속성이 애니메이션됩니다. 성능과 제어를 위해서는 구체적 속성을 나열하세요. 여러 트랜지션은 쉼표로 구분합니다. 트랜지션은 :hover가 아니라 요소의 기본 상태에 두어야 되돌릴 때도 애니메이션이 재생됩니다.
.btn {
background: blue;
/* shorthand: property duration timing-function delay */
transition: background 0.3s ease 0s;
/* common usage */
transition: all 0.3s ease;
/* multiple properties (comma-separated) */
transition: background 0.3s, transform 0.2s ease-out;
/* list the same duration on many properties */
transition: 0.3s;
}
.btn:hover {
background: darkblue;
transform: scale(1.05);
}타이밍 함수
타이밍 함수는 가속을 제어합니다. ease(기본값)는 부드럽습니다. ease-out은 UI에서 가장 반응이 빠르게 느껴집니다(빠른 시작, 느린 끝). linear는 대부분의 움직임에서 부자연스럽습니다. cubic-bezier(x1,y1,x2,y2)로 커스텀 곡선을 만들 수 있고, y축 값을 0~1 밖으로 하면 오버슈트/바운스가 생깁니다. steps(n)은 불연속 점프를 만들며 스프라이트 시트 애니메이션에 유용합니다.
.ease { transition: all 0.3s ease; } /* default, smooth start/end */
.linear { transition: all 0.3s linear; } /* constant speed */
.ease-in { transition: all 0.3s ease-in; } /* slow start */
.ease-out { transition: all 0.3s ease-out; } /* slow end (feels responsive) */
.ease-in-out { transition: all 0.3s ease-in-out; }/* slow both ends */
/* cubic-bezier: custom curve (P1x P1y P2x P2y) */
.custom { transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55); } /* overshoot */
/* steps: jump in increments */
.steps { transition: all 0.3s steps(4, end); }다중 & 계단식 트랜지션
속성마다 다른 지속 시간과 지연을 줄 수 있습니다 — 한 속성이 끝난 뒤 다른 속성이 시작되는 안무 효과에 유용합니다. transition-delay는 리스트에 계단식 등장을 만들며, nth-child와 결합해 아이템마다 점진적으로 지연시킬 수 있습니다. 퇴장에도 지연을 쓸 수 있지만 주의하세요: 지연 중 마우스를 뗐을 때 등장이 갑자기 끊길 수 있습니다.
.card {
/* different durations per property */
transition: transform 0.2s ease-out, box-shadow 0.4s ease;
/* delay creates staggered effect */
transition: background 0.3s, color 0.3s 0.1s; /* color starts after 0.1s */
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
background: #f5f5f5;
}
/* stagger multiple elements via transition-delay */
.item:nth-child(1) { transition-delay: 0s; }
.item:nth-child(2) { transition-delay: 0.1s; }
.item:nth-child(3) { transition-delay: 0.2s; }트랜지션 가능한 속성
어떤 속성은 부드럽게 전환되지만 어떤 속성은 버벅임을 유발합니다. GPU 가속의 주인공은 transform, opacity, filter입니다. 색상과 box-shadow는 괜찮습니다(레이아웃이 아닌 페인트를 유발). width, height, margin, top, left의 전환은 피하세요 — 매 프레임 레이아웃 재계산이 일어납니다. 크기 변화 애니메이션에는 transform: scale()을 사용하세요.
/* WELL-SUPPORTED & performant */
.good {
transition: transform 0.3s, opacity 0.3s, filter 0.3s;
}
/* OK but may trigger paint */
.okay {
transition: background-color 0.3s, color 0.3s, border-color 0.3s;
transition: box-shadow 0.3s;
}
/* AVOID: triggers layout (reflow) - janky */
.bad {
transition: width 0.3s, height 0.3s, margin 0.3s, top 0.3s, left 0.3s;
}
/* if you must animate size, use transform: scale() instead */
.smooth-resize { transition: transform 0.3s; }트랜지션 발동 조건
트랜지션은 속성 값이 변하면 발동합니다: 의사 클래스 상태(:hover, :focus, :checked), 클래스 변화(JS가 추가/제거), 미디어 쿼리 변화 등입니다. 이전 값과 새 값 사이를 부드럽게 보간합니다. 트랜지션은 양방향(들어갈 때/나갈 때) 모두 재생됩니다. 더 복잡하거나 반복되는 다단계 움직임에는 @keyframes 애니메이션을 사용하세요.
/* hover trigger */
.btn { transition: all 0.3s; }
.btn:hover { transform: scale(1.1); }
/* focus trigger (accessibility-friendly) */
.input { transition: border-color 0.2s; }
.input:focus { border-color: blue; }
/* class change via JavaScript */
.modal { transition: opacity 0.3s; opacity: 0; }
.modal.open { opacity: 1; }
/* media query trigger */
.box { transition: width 0.3s; width: 100%; }
@media (min-width: 768px) { .box { width: 50%; } }
/* CSS state triggers (:checked) */
.toggle:checked + .menu { transition: max-height 0.3s; max-height: 500px; }애니메이션
@keyframes
@keyframes는 애니메이션의 시퀀스를 정의합니다. 정지점은 퍼센트(0%, 50%, 100%) 또는 from/to(0%/100%와 동일)로 표기합니다. 정지점에 없는 속성은 정의된 정지점 사이를 보간합니다. 애니메이션 가능한 속성(transform, opacity, 색상)만 동작합니다 — display, position 등은 안 됩니다. @keyframes는 한 번 정의해 여러 요소에서 재사용하세요.
@keyframes bounce {
0% { transform: translateY(0); }
50% { transform: translateY(-30px); }
100% { transform: translateY(0); }
}
/* from/to shorthand (2-stop) */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
/* multiple properties at each stop */
@keyframes pulse {
0% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(1.1); }
100% { opacity: 1; transform: scale(1); }
}애니메이션 축약형
animation 축약형은 8개 속성을 이 순서로 담습니다: name duration timing-function delay iteration-count direction fill-mode play-state. 최소한 name과 duration이 필요합니다. 참고: 시간 값은 두 개가 나올 수 있는데, 첫 번째가 duration이고 두 번째가 delay입니다. 프로덕션에서는 가독성을 위해 개별 속성이나 부분 축약형을 권합니다.
.bouncing {
/* longhand */
animation-name: bounce;
animation-duration: 1s;
animation-timing-function: ease-in-out;
animation-delay: 0s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-fill-mode: both;
animation-play-state: running;
/* shorthand: name duration timing delay count direction fill-mode play-state */
animation: bounce 1s ease-in-out 0s infinite alternate both running;
/* minimal: name + duration */
animation: bounce 1s;
}반복 & 방향
animation-iteration-count는 반복을 제어합니다 — infinite는 영원히, 소수 값은 부분 사이클만 재생합니다. animation-direction: alternate는 다음 반복에서 애니메이션을 앞으로 재생했다가 뒤로 재생해 매끄러운 바운스를 만듭니다. reverse는 뒤로, alternate-reverse는 뒤로 시작합니다. alternate는 펄스나 호흡 같은 왕복 운동에 필수입니다.
/* iteration-count: how many times to play */
.once { animation-iteration-count: 1; } /* default */
.thrice { animation-iteration-count: 3; }
.forever { animation-iteration-count: infinite; }
.fractional { animation-iteration-count: 0.5; } /* half a play */
/* direction */
.normal { animation-direction: normal; } /* 0% -> 100% */
.reverse { animation-direction: reverse; } /* 100% -> 0% */
.alternate { animation-direction: alternate; } /* forward, then backward */
.alternate-rev { animation-direction: alternate-reverse; }애니메이션 fill 모드
animation-fill-mode는 애니메이션 실행 전후의 스타일을 제어합니다. none(기본값)은 끝나면 요소의 일반 스타일로 되돌아갑니다. forwards는 끝난 뒤 마지막 키프레임 상태를 유지합니다 — 등장 애니메이션에서 요소가 튕겨 돌아가지 않게 하는 필수 값입니다. backwards는 지연 동안 첫 키프레임을 적용합니다. both는 둘 다입니다. 1회성 등장에는 forwards 또는 both를 쓰세요.
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
/* none (default): reverts to original styles before/after */
.none { animation: slideIn 1s; }
/* forwards: holds the final (to) state after finishing */
.forwards { animation: slideIn 1s forwards; }
/* backwards: applies the (from) state during delay */
.backwards { animation: slideIn 1s 0.5s backwards; }
/* both: applies from during delay AND holds to after */
.both { animation: slideIn 1s 0.5s both; }재생 상태 & 일시정지
animation-play-state: paused는 애니메이션을 현재 프레임에서 멈추고, running은 재개합니다. hover나 JS 토글 클래스로 일시정지하는 가장 깔끔한 방법입니다 — 애니메이션이 재시작 대신 위치를 기억합니다. 성능을 위해 IntersectionObserver로 화면 밖으로 스크롤된 요소의 애니메이션을 일시정지하세요. 접근성을 위해 reduced-motion 미디어 쿼리와 조합하세요.
.anim { animation: spin 2s linear infinite; }
/* pause on hover */
.anim:hover { animation-play-state: paused; }
/* pause via class (JS toggle) */
.anim.paused { animation-play-state: paused; }
/* useful for performance: pause off-screen animations */
.offscreen { animation-play-state: paused; }
/* resume */
.resumed { animation-play-state: running; }미디어 쿼리
기본 문법
미디어 쿼리는 조건부로 스타일을 적용합니다. (min-width: 768px)은 모바일 우선 방식으로 768px 이상 화면에 적용됩니다. and(둘 다 일치), 쉼표(OR), not(부정)으로 조합합니다. 모바일 우선(min-width) 방식이 권장됩니다: 작은 화면용 기본 스타일을 쓰고 큰 화면에서 점진적으로 확장하세요. 작은 화면 CSS를 가볍게 유지할 수 있습니다.
/* apply styles when viewport is at least 768px wide */
@media (min-width: 768px) {
.grid { grid-template-columns: repeat(2, 1fr); }
}
/* combine conditions with and */
@media (min-width: 768px) and (max-width: 1024px) {
.box { padding: 20px; }
}
/* list of queries (OR) */
@media (max-width: 600px), (min-width: 1200px) {
.text { font-size: 14px; }
}
/* negate with not */
@media not print {
.screen-only { display: block; }
}최소/최대 너비 브레이크포인트
브레이크포인트는 특정 기기가 아닌 콘텐츠 기준으로 잡아야 하지만, 흔한 구간(640px 태블릿, 1024px 데스크톱, 1280px 대형)도 잘 맞습니다. 모바일 우선은 min-width를 쓰고 모바일 스타일을 기본으로 한다는 뜻입니다. 새로운 범위 문법(width >= 768px)이 더 읽기 쉽고 모든 모던 브라우저에서 지원되며, 길고 복잡한 min/max 조합을 대체합니다.
/* common breakpoints (mobile-first) */
/* base styles (mobile) */
.container { padding: 16px; }
@media (min-width: 640px) { /* small tablets */
.container { padding: 24px; }
}
@media (min-width: 1024px) { /* desktops */
.container { padding: 32px; max-width: 1200px; margin: 0 auto; }
}
@media (min-width: 1280px) { /* large screens */
.container { max-width: 1400px; }
}
/* range syntax (newer, cleaner) */
@media (width >= 768px) and (width <= 1024px) {
.box { padding: 20px; }
}방향 & 화면 비율
너비 외에 미디어 쿼리는 방향(portrait/landscape), aspect-ratio, hover 능력, 포인터 타입도 대상으로 삼습니다. @media (hover: hover)는 실제 포인터가 있는 기기에서만 hover 스타일이 적용되게 합니다(터치의 끈적한 hover 방지). (pointer: coarse)는 터치 기기를 대상으로 합니다 — 탭 대상을 키우기에 완벽합니다. 이런 기능들로 기기에 맞는 인터페이스가 가능해집니다.
/* portrait vs landscape */
@media (orientation: portrait) {
.grid { grid-template-columns: 1fr; }
}
@media (orientation: landscape) {
.grid { grid-template-columns: 1fr 1fr; }
}
/* aspect ratio */
@media (min-aspect-ratio: 16/9) {
.video { width: 100%; height: auto; }
}
/* hover capability: devices that support hover */
@media (hover: hover) {
.btn:hover { background: darkblue; }
}
/* pointer: fine (mouse) vs coarse (touch) */
@media (pointer: coarse) {
.btn { padding: 16px 32px; } /* bigger tap targets */
}인쇄 스타일
인쇄 미디어 쿼리는 인쇄 시 페이지 모양을 다룹니다. 내비게이션, 광고, 인터랙티브 요소를 숨기고, 콘텐츠를 전체 너비로 확장하고, 잉크 절약을 위해 검은색-흰색으로 강제합니다. break-inside: avoid는 요소가 페이지를 가르지 않게 하고, break-before: page는 강제로 페이지를 나눕니다. 링크의 ::after 트릭으로 인쇄 시 URL을 보여줄 수 있습니다 — 인쇄용 글에 매우 유용합니다.
@media print {
/* hide non-essential UI */
.nav, .sidebar, .ads, .comments { display: none; }
/* expand main content */
.main { width: 100%; margin: 0; }
/* force black text on white */
body { color: black; background: white; }
/* avoid breaking inside elements */
h1, h2, img, table { break-inside: avoid; }
/* page breaks before sections */
h1 { break-before: page; }
/* show URLs after links */
a[href]::after { content: " (" attr(href) ")"; }
}prefers-reduced-motion & color-scheme
prefers-reduced-motion은 중요한 접근성 기능입니다 — 전정 장애가 있는 사용자는 움직임을 최소화해야 합니다. 항상 애니메이션을 비활성화하거나 단축하는 reduced-motion 폴백을 제공하세요. prefers-color-scheme은 사용자 OS 테마에 자동으로 맞춥니다. 다크 모드에서는 어두운 배경 위에서 대비, 이미지, 그림자도 함께 고려하세요.
/* respect users who prefer less motion */
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* light/dark mode */
@media (prefers-color-scheme: dark) {
body { background: #1a1a1a; color: #eee; }
.card { background: #2a2a2a; }
}
@media (prefers-color-scheme: light) {
body { background: white; color: #333; }
}반응형 디자인
clamp() 유동 타이포그래피
clamp(min, preferred, max)는 경계 사이에서 유동적으로 스케일되는 값을 만듭니다 — 미디어 쿼리 없이 적응하는 타이포그래피와 간격에 완벽합니다. preferred 값은 보통 vw 기반 표현식입니다. 이로써 많은 브레이크포인트를 없앨 수 있습니다. 접근성을 위해 rem과 함께 쓰세요(사용자가 루트 폰트 크기를 조절할 수 있음). 유동 타이포는 모든 기기에서 가독성과 체감 성능을 높입니다.
/* clamp(min, preferred, max) - fluid between bounds */
h1 {
/* scales from 1.5rem to 3rem as viewport grows */
font-size: clamp(1.5rem, 5vw, 3rem);
}
p {
/* readable body text on any screen */
font-size: clamp(1rem, 2.5vw, 1.25rem);
}
/* fluid spacing */
.section {
padding: clamp(1rem, 4vw, 3rem);
}
/* fluid container width */
.container {
width: clamp(280px, 90vw, 1200px);
margin: 0 auto;
}모바일 우선 접근
모바일 우선은 작은 화면 스타일을 기본으로 쓰고, min-width 미디어 쿼리로 큰 화면을 확장한다는 뜻입니다. CSS가 가벼워지고(모바일은 필요한 것만 내려받음) 콘텐츠 우선 사고방식을 강제합니다. 데스크톱 우선(max-width)은 모바일이 데스크톱 스타일을 내려받아 덮어쓰게 만듭니다 — 느리고 유지보수가 어렵습니다.
/* base = mobile styles (no media query) */
.card {
width: 100%;
padding: 12px;
font-size: 14px;
}
/* progressively enhance for larger screens */
@media (min-width: 640px) {
.card { width: 50%; padding: 16px; }
}
@media (min-width: 1024px) {
.card { width: 33.33%; padding: 24px; font-size: 16px; }
}
/* AVOID desktop-first (forces mobile to override) */
/* @media (max-width: 640px) { ... } */컨테이너 쿼리
컨테이너 쿼리는 게임 체인저입니다: 컴포넌트가 뷰포트가 아닌 부모의 크기에 반응하게 합니다. 카드가 좁은 사이드바에 있든 넓은 메인 영역에 있든 레이아웃을 적응시킵니다 — 진정한 컴포넌트 단위 반응형입니다. container-type: inline-size는 너비를 쿼리합니다(가장 효율적). 컨테이너에 이름을 붙여 특정 대상으로 쿼리하거나, 이름 없이 가장 가까운 조상을 쿼리할 수 있습니다.
/* make an element a query container */
.sidebar {
container-type: inline-size;
container-name: sidebar;
}
/* styles based on the container's size, not the viewport */
@container sidebar (min-width: 400px) {
.card {
grid-template-columns: 1fr 1fr;
}
}
/* inline-size = width only (most common, performant) */
/* size = both dimensions (more expensive) */
/* unnamed container query (uses nearest ancestor) */
.card-wrap { container-type: inline-size; }
@container (min-width: 500px) {
.card { flex-direction: row; }
}뷰포트 단위
vh/vw는 뷰포트의 백분율입니다. 문제: 모바일에서 100vh는 주소 표시줄이 나타나거나 숨을 때 변해 버벅입니다. 새로운 svh/lvh/dvh 단위가 이를 해결합니다 — dvh는 동적으로 갱신되고, svh는 가장 작은 안정 값을 씁니다. vmin/vmax는 뷰포트의 짧은/긴 쪽입니다 — 스케일되는 정사각형 요소에 좋습니다. vw 폰트 크기는 calc나 clamp로 rem/px 하한과 함께 쓰세요.
.hero {
height: 100vh; /* full viewport height */
/* small viewport units: account for mobile browser chrome */
height: 100svh; /* smallest possible viewport (stable) */
height: 100lvh; /* largest possible viewport */
height: 100dvh; /* dynamic - updates as chrome shows/hides */
}
.full-width { width: 100vw; }
.responsive-font { font-size: 5vw; }
/* vmin/vmax: smaller/larger of width or height */
.square { width: 50vmin; height: 50vmin; }
.banner { height: 30vmax; }
/* combining with calc for safety */
.hero-text { font-size: calc(16px + 2vw); }aspect-ratio
aspect-ratio는 width:height 비율을 자동으로 유지합니다 — 반응형 동영상을 위한 padding-top 핵은 이제 그만입니다. 요소의 높이가 너비에서 파생됩니다(반대도 가능). 이미지에 object-fit: cover와 결합하면 이미지 로딩 중 레이아웃 시프트를 막습니다. 미디어 공간을 확보하고 누적 레이아웃 시프트(CLS — Core Web Vital)를 피하는 가장 깔끔한 방법입니다.
/* maintain a 16:9 ratio regardless of width */
.video {
aspect-ratio: 16 / 9;
width: 100%;
}
/* square avatar */
.avatar {
aspect-ratio: 1;
width: 80px;
border-radius: 50%;
}
/* golden ratio card */
.card {
aspect-ratio: 1.618;
}
/* combined with object-fit for responsive images */
.thumb {
aspect-ratio: 4 / 3;
width: 100%;
object-fit: cover;
}커스텀 속성 (변수)
변수 정의 & 사용
CSS 커스텀 속성(변수)은 --name으로 선언하고 var(--name)으로 사용합니다. :root에 정의하면 전역으로 접근할 수 있고, 원하는 요소에 스코프를 둘 수도 있습니다. 전처리기 변수와 달리 살아 있습니다: 변수를 바꾸면 모든 사용처가 실시간으로 갱신되며, 캐스케이드와 상속도 됩니다. var()는 두 번째 인수로 폴백을 받으며, 변수가 정의되지 않았을 때 사용됩니다.
:root {
--primary: #3490dc;
--spacing: 16px;
--max-width: 1200px;
}
.button {
background: var(--primary);
padding: var(--spacing);
/* with fallback value (used if --primary undefined) */
color: var(--text-color, #333);
}
/* override in a specific scope */
.dark-theme {
--primary: #5a9fee;
}테마 & 다크 모드
커스텀 속성은 테마를 아주 쉽게 만듭니다: 의미적 변수(--bg, --text, --primary)를 정의하고 [data-theme] 셀렉터에서 덮어씁니다. <html>의 data-theme 속성을 토글하면 전체 테마가 즉시 바뀝니다 — 스타일시트를 복제할 필요가 없습니다. prefers-color-scheme과 결합하면 사용자의 수동 덮어쓰기를 존중하는 자동 다크 모드가 됩니다. 현대적이고 고성능인 테마 방식입니다.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--primary: #3490dc;
}
[data-theme="dark"] {
--bg: #1a1a1a;
--text: #ffffff;
--primary: #5a9fee;
}
body {
background: var(--bg);
color: var(--text);
}
/* auto dark mode via media query */
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #1a1a1a;
--text: #ffffff;
}
}캐스케이드 & 상속
커스텀 속성은 일반 CSS처럼 캐스케이드되고 상속됩니다. .card에 정의된 변수는 .card와 모든 자손에게 유효하지만 형제에게는 아닙니다. 각 요소는 자기 스코프에서 변수의 계산 값을 읽습니다. @property(신규)는 문법, 초기 값, 상속 플래그를 갖는 타입 변수를 선언하게 해 줍니다 — 커스텀 속성의 부드러운 전환과 애니메이션을 가능하게 합니다.
:root { --color: blue; } /* global */
.card { --color: green; } /* scoped to .card */
.card .inner { color: var(--color); } /* green - inherits from .card */
/* variables inherit like other properties */
.parent { --size: 20px; }
.child { font-size: var(--size); } /* 20px via inheritance */
/* but: each element reads its own computed value */
.a { --x: 10px; }
.b { /* --x is NOT defined here, even if .a is sibling */ }
/* @property: typed variables with initial value */
@property --angle {
syntax: "<angle>";
inherits: false;
initial-value: 0deg;
}JavaScript 연동
CSS 변수는 JavaScript에서 완전히 접근 가능합니다. getComputedStyle(el).getPropertyValue('--name')으로 읽고(문자열 반환, 보통 앞에 공백이 있어 trim 필요), el.style.setProperty('--name', value)로 설정합니다. 커스텀 속성은 강력한 JS-CSS 다리가 됩니다: JS에서 변수 하나를 바꾸면 CSS가 즉시 반응합니다 — 스크롤 기반 효과, 테마, 동적 레이아웃에 완벽합니다.
/* read a variable */
const styles = getComputedStyle(document.documentElement);
const primary = styles.getPropertyValue("--primary"); /* "#3490dc" */
/* set a variable globally */
document.documentElement.style.setProperty("--primary", "#ff0000");
/* set on a specific element */
el.style.setProperty("--spacing", "24px");
/* inline style with variable */
<div style="--rotate: 45deg"></div>
/* useful pattern: expose JS values to CSS */
.root { --scroll: 0; }
.box { transform: rotate(calc(var(--scroll) * 1deg)); }폴백 & 체이닝
var()는 두 번째 인수로 폴백을 지원하며, 변수가 정의되지 않았을 때만 사용됩니다(유효하지 않을 때가 아님 — 유효하지 않은 값은 속성 전체가 기본값으로 돌아가게 합니다). 폴백은 체이닝할 수 있습니다: var(--a, var(--b, #default)). 점진적 향상과 서드파티 컴포넌트 통합에 유용합니다. @supports (--x: 0)로 지원 여부를 감지할 수 있지만, 모든 모던 브라우저가 커스텀 속성을 지원합니다.
.box {
/* single fallback */
color: var(--undefined, #333);
/* chained: try --primary, fall back to --blue, then #00f */
color: var(--primary, var(--blue, #0000ff));
/* fallback in calc() */
width: calc(100% - var(--sidebar, 250px));
/* invalid values fall back to inherited/default */
/* var() itself doesn't fail — the property does */
}
/* feature detection for custom property support */
@supports (--custom: property) {
:root { --modern: true; }
}필터
필터 함수
filter는 요소에 시각 효과를 적용합니다. brightness/contrast/saturate는 배수(1 = 보통)나 퍼센트를 받습니다. hue-rotate는 모든 색조를 각도만큼 이동합니다. 여러 필터는 왼쪽에서 오른쪽으로 체이닝됩니다. 흔한 사용: hover 시 이미지 흑백화, 빈티지 사진 효과, 배경 어둡게 하기. 필터는 요소와 배경, 테두리, 자식에 모두 영향을 줍니다.
.blur { filter: blur(4px); } /* gaussian blur in px */
.bright { filter: brightness(1.5); } /* 1 = normal, >1 brighter */
.contrast { filter: contrast(200%); } /* 100% = normal */
.gray { filter: grayscale(100%); } /* 0-100% */
.sepia { filter: sepia(80%); }
.hue { filter: hue-rotate(90deg); } /* rotate hue */
.invert { filter: invert(100%); } /* invert colors */
.saturate { filter: saturate(2); } /* 1 = normal */
.opacity { filter: opacity(50%); }
/* combine multiple filters (left-to-right) */
.vintage { filter: sepia(60%) contrast(110%) brightness(90%) saturate(1.2); }drop-shadow
drop-shadow는 box-shadow의 필터 버전입니다 — 하지만 박스가 아닌 요소의 실제 알파 모양을 따릅니다. 즉 그림자가 PNG/SVG 잘라낸 모양과 불규칙한 형태에 딱 붙습니다. 아이콘 그림자, 빛나는 로고, 비직사각형 요소에 사용하세요. 여러 drop-shadow를 겹칠 수 있습니다. 참고: box-shadow보다 비쌀 수 있으니 절제해서 쓰세요.
/* drop-shadow follows the alpha shape (unlike box-shadow) */
.cutout {
filter: drop-shadow(4px 4px 8px rgba(0,0,0,0.4));
}
/* shadows on PNG with transparency - hugs the shape */
.logo {
filter: drop-shadow(0 4px 6px rgba(0,0,0,0.3));
}
/* glow effect on text or SVG */
.icon {
filter: drop-shadow(0 0 8px rgba(0, 150, 255, 0.8));
}
/* multiple drop-shadows layer */
.deep {
filter: drop-shadow(0 1px 1px rgba(0,0,0,0.5))
drop-shadow(0 2px 4px rgba(0,0,0,0.3));
}backdrop-filter
backdrop-filter는 요소 뒤의 모든 것에 필터를 적용합니다 — 글래스모피즘의 핵심입니다. 반투명 배경에 backdrop-filter: blur()를 더하면 서리 낀 유리 느낌이 됩니다. Safari를 위해 항상 -webkit- 접두사를 포함하세요. 효과가 보이려면 요소 배경에 약간의 투명도가 필요합니다. saturate()와 결합하면 더 생생해지고, 미묘한 테두리로 가장자리 반사를 흉내 낼 수 있습니다.
/* frosted glass effect */
.glass {
background: rgba(255, 255, 255, 0.2);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px); /* Safari */
border: 1px solid rgba(255, 255, 255, 0.3);
}
/* saturate + blur for vivid glass */
.vivid-glass {
backdrop-filter: blur(16px) saturate(180%);
}
/* dark glass for dark mode */
.dark-glass {
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(12px);
}필터 조합
여러 필터는 왼쪽에서 오른쪽으로 적용되므로 순서가 결과에 영향을 줍니다(예: grayscale이 hue-rotate보다 먼저면 회전시킬 색조가 없습니다). 필터는 애니메이션 가능하고 GPU 가속됩니다 — hover 효과에 좋습니다. filter를 mix-blend-mode와 함께 쓰면 요소를 배경과 블렌딩할 수 있습니다. 동적 제어에는 필터 체인을 커스텀 속성에 담아 JS로 갱신하세요.
/* order matters: each filter feeds the next */
.artsy {
filter: grayscale(100%) contrast(150%) brightness(110%);
}
/* animate filters smoothly */
img { transition: filter 0.3s; }
img:hover { filter: grayscale(0%) saturate(1.4); }
/* use CSS variables for dynamic filters */
.dynamic { filter: var(--photo-filter, none); }
/* layer with other effects */
.complex {
filter: blur(1px) brightness(1.1);
mix-blend-mode: multiply;
opacity: 0.9;
}필터 성능
필터는 GPU 가속되지만 공짜는 아닙니다. 전체 화면 요소의 큰 블러는 과도한 리페인트와 버벅임을 유발합니다. 특히 모바일에서 그렇습니다. 블러 반지름을 작게 유지하고, 필터 영역을 제한하며, 애니메이션 전에 will-change: filter를 적용하세요. backdrop-filter는 특히 비쌉니다 — 전체 섹션이 아니라 작은 UI 요소에 사용하세요. contain: paint는 리페인트 영역을 격리해 성능을 개선합니다.
/* AVOID: large blur on full-screen elements */
.janky { filter: blur(20px); } /* causes repaints */
/* BETTER: pre-blurred image, or limit blur area */
.smooth {
filter: blur(2px); /* small radius is cheaper */
}
/* backdrop-filter is expensive - use sparingly */
/* contain: paint can limit repaint area */
.contained {
contain: paint;
backdrop-filter: blur(10px);
}
/* will-change prepares the GPU layer */
.prepared {
will-change: filter;
filter: blur(4px);
}의사 요소
::before & ::after
::before와 ::after는 요소의 실제 콘텐츠 앞/뒤에 생성 콘텐츠를 삽입합니다. content 속성이 필수입니다(장식용이라면 빈 문자열이라도). 콘텐츠는 텍스트, 이스케이프된 유니코드, attr()로 가져온 속성 값이 될 수 있습니다. 이 의사 요소들은 기본적으로 inline이므로 박스형 장식에는 display: block을 설정하세요. 아이콘, 장식선, 인용문, float 해제에 완벽합니다.
.quote::before { content: "\201C"; } /* opening quote */
.quote::after { content: "\201D"; } /* closing quote */
/* icon via Unicode */
.warning::before { content: "\26A0"; margin-right: 6px; }
/* decorative element with content: "" */
.card::after {
content: "";
display: block;
width: 50px; height: 2px;
background: currentColor;
margin-top: 12px;
}
/* content can use attributes */
a[href^="http"]::after {
content: " (" attr(href) ")";
font-size: 0.8em;
}::first-letter & ::first-line
::first-letter는 첫 문자를 스타일링합니다 — 글의 드롭캡(drop cap)에 완벽합니다. ::first-line은 첫 줄을 스타일링하며, 뷰포트 너비에 따라 동적으로 조정됩니다. 둘 다 블록 레벨 요소에서만 동작합니다. ::first-letter는 첫 문자 앞에 다른 콘텐츠(이미지 등)가 없을 때만 적용됩니다. 에디토리얼 레이아웃의 타이포그래피 필수 요소입니다.
article p::first-letter {
font-size: 3em;
font-weight: bold;
float: left;
line-height: 0.8;
margin-right: 8px;
/* drop cap effect */
}
article p::first-line {
text-transform: uppercase;
letter-spacing: 1px;
font-weight: bold;
}
/* only works on block-level elements */
/* affects the first formatted line (reflows with width) */::selection
::selection은 사용자가 하이라이트한 텍스트를 스타일링합니다. 적용되는 속성은 소수입니다: color, background-color, text-shadow, text-decoration. 선택 색상을 사이트 브랜드에 맞추는 데 사용하세요. 전역으로 ::selection을 쓰거나 특정 요소로 스코프할 수 있습니다. 구형 Firefox는 ::-moz-selection이 필요했지만, 현대 Firefox는 표준 ::selection을 지원합니다.
/* style highlighted/selected text */
::selection {
background: #b3d4fc;
color: black;
text-shadow: none;
}
/* scoped to specific elements */
p::selection { background: yellow; }
.highlight::selection { background: gold; color: #333; }
/* note: only a few properties work:
color, background-color, text-shadow,
text-decoration (and its longhands) */
/* firefox historically used ::-moz-selection */::placeholder & ::marker
::placeholder는 폼 입력의 플레이스홀더 텍스트를 스타일링합니다 — Firefox가 반투명 기본값을 쓰므로 opacity: 1을 설정하세요. ::marker는 목록 불릿이나 숫자를 스타일링하며 제한된 속성(color, content, font, direction)을 지원합니다. 커스텀 콘텐츠(유니코드, 카운터)로 불릿을 교체할 수도 있습니다. 이 의사 요소들은 폼과 리스트 스타일링을 디자이너의 완전한 통제 아래 둡니다.
/* style input placeholder text */
input::placeholder {
color: #999;
font-style: italic;
opacity: 1; /* Firefox applies opacity < 1 by default */
}
/* style list item markers (bullets/numbers) */
ul li::marker {
color: red;
font-size: 1.2em;
content: "\25CF"; /* custom bullet */
}
ol li::marker {
content: counter(list-item) ". ";
color: blue;
font-weight: bold;
}
/* ::marker supports: color, content, font properties,
direction, unicode-bidi, text-transform, white-space */생성 콘텐츠 & 카운터
::before/::after의 생성 콘텐츠에는 counter() 값, 속성 값(attr()), 문자열 리터럴이 들어갈 수 있습니다 — 추가 DOM 없이 CSS만으로 번호, 아이콘, 툴팁이 가능합니다. counters()는 '1.2.3' 같은 중첩 번호를 만듭니다. attr(data-tooltip)과 hover 트랜지션으로 만든 툴팁은 JS 라이브러리의 가벼운 대안입니다. 주의: 생성 콘텐츠는 DOM에 없고 일부 스크린 리더가 읽지 않습니다 — 중요한 콘텐츠를 넣지 마세요.
/* counter in generated content */
h2::before {
content: "Section " counter(section) ": ";
color: gray;
}
/* attr() reads HTML attributes */
a::after {
content: attr(data-icon);
}
/* counters() for nested numbering */
ol { counter-reset: item; }
li { display: block; }
li::before {
content: counters(item, ".") " ";
counter-increment: item;
}
/* CSS-only tooltip */
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
background: black; color: white;
padding: 4px 8px;
opacity: 0; transition: opacity 0.2s;
}
.tooltip:hover::after { opacity: 1; }카운터
counter-reset & counter-increment
CSS 카운터로 JavaScript 없이 요소에 번호를 매길 수 있습니다. counter-reset은 카운터를 초기화합니다(기본 0이지만 다른 값으로 시작 가능). counter-increment는 증가시킵니다(기본 1이지만 임의의 정수 — 음수도 가능). 값은 content 안의 counter()로 표시합니다. 카운터는 리셋된 요소와 그 자손에 스코프되므로 중첩 번호 매기기가 가능합니다.
body { counter-reset: section; } /* initialize to 0 */
h2 {
counter-increment: section; /* +1 each h2 */
}
h2::before {
content: "Section " counter(section) ": ";
}
/* custom increment value */
ol { counter-reset: item; }
li { counter-increment: item 1; } /* +1 (default) */
li.big { counter-increment: item 2; } /* +2 */
/* reset to a custom starting value */
.start-5 { counter-reset: item 4; } /* next increment = 5 */counter() 함수
counter(name)은 카운터의 현재 값을 출력하고, counter(name, style)은 리스트 스타일을 적용합니다: decimal(기본값), lower/upper-alpha, lower/upper-roman, disc, square 등. 여러 카운터를 병렬로 돌리고 content에서 조합할 수 있습니다 — 장별 그림 번호(그림 3-2)에 완벽합니다. 카운터 값은 렌더 시점에 계산되므로 DOM이 바뀌면 자동 갱신됩니다.
body { counter-reset: section; }
h2 { counter-increment: section; }
h2::before {
content: "Chapter " counter(section) ". ";
color: navy;
}
/* counter style (decimal, lower-alpha, upper-roman, etc.) */
h2::before {
content: counter(section, upper-roman) ". ";
}
/* multiple counters */
body { counter-reset: section figure; }
h2 { counter-increment: section; }
figcaption { counter-increment: figure; }
figcaption::before {
content: "Figure " counter(section) "-" counter(figure) ": ";
}counters()로 중첩 카운터
counters(name, separator)는 중첩 카운터 함수입니다: 모든 조상 스코프의 카운터 값을 주어진 문자열로 구분해 이어붙입니다. 이로써 '1.2.3' 같은 개요 번호가 자동으로 만들어집니다 — 같은 카운터 이름이 중첩 <ol>마다 리셋됩니다. 복수형 counters()가 없으면 중첩 리스트가 모두 같은 번호를 공유하게 됩니다. 구분자는 '.'이나 '-' 등 아무 문자열이 될 수 있습니다.
ol { counter-reset: item; list-style: none; }
li::before {
counter-increment: item;
/* counters() concatenates ancestor counters with separator */
content: counters(item, ".") " ";
}
/* produces: 1 / 1.1 / 1.2 / 2 / 2.1 / 2.1.1 ... */
<ol>
<li>Item
<ol>
<li>Sub-item</li>
<li>Sub-item</li>
</ol>
</li>
<li>Item</li>
</ol>
/* custom separator */
li::before { content: counters(item, "-") ": "; }카운터 스타일링
카운터는 많은 내장 스타일을 지원합니다: decimal, upper-roman, lower-alpha, lower-greek, cjk-decimal 등. @counter-style로 심볼 세트, 시스템(cyclic, additive, extends), pad(선행 0), prefix/suffix, range 같은 옵션으로 커스텀 스타일을 정의할 수 있습니다. JavaScript 없이 테마 리스트, 이모지 불릿, 지역화된 번호 매기기에 좋습니다.
/* built-in styles */
.decimal { content: counter(c, decimal); }
.roman { content: counter(c, upper-roman); } /* I, II, III */
.alpha { content: counter(c, lower-alpha); } /* a, b, c */
.greek { content: counter(c, lower-greek); } /* alpha, beta, gamma */
.cjk { content: counter(c, cjk-decimal); } /* CJK numerals */
/* @counter-style: define a custom style */
@counter-style thumbs {
system: cyclic;
symbols: "\1F44D"; /* thumbs up emoji */
suffix: " ";
}
.like-list { list-style-type: thumbs; }
/* leading zeros via pad */
@counter-style padded {
system: extends decimal;
pad: 3 "0"; /* 001, 002, ... */
}실용 카운터 패턴
카운터는 번호 단계 표시기, 목차, 개요에서 빛을 발합니다. ::before에 원형 배지, 색상, 숫자를 스타일링하면 수동 번호 없이 번호 단계 리스트를 만들 수 있습니다. DOM을 편집하면 번호가 자동 갱신됩니다. 주의: 카운터 값은 JavaScript에서 쉽게 읽을 수 없습니다 — 표시 전용입니다. 개수 기반 로직에는 JS나 CSS :nth-child를 사용하세요.
/* numbered steps */
.steps { counter-reset: step; }
.steps li { counter-increment: step; }
.steps li::before {
content: counter(step);
display: inline-block;
width: 28px; height: 28px;
border-radius: 50%;
background: var(--primary);
color: white;
text-align: center;
line-height: 28px;
margin-right: 10px;
}
/* "you've completed N sections" via counters (limited -
counters can't be read by JS easily, use them for display) */다단 레이아웃
column-count & column-width
다단 레이아웃은 콘텐츠를 신문처럼 여러 단으로 흐르게 합니다. column-count는 단 수를 고정하고, column-width는 맞는 만큼 250px 단을 만들게 합니다(미디어 쿼리 없이 반응형). columns 축약형은 count와/또는 width를 받습니다. 다단은 긴 읽기 텍스트에 이상적이지만, 짧은 콘텐츠는 단 높이가 불균형해질 수 있으니 주의하세요.
.article {
/* fixed number of columns */
column-count: 3;
/* OR width-based (browser decides count) */
column-width: 250px;
/* shorthand (count width) */
columns: 3 250px;
columns: 3; /* 3 columns */
columns: 250px; /* 250px columns, auto count */
}
/* responsive: width lets columns collapse on small screens */
.fluid { column-width: 200px; } /* 1 column on mobile, more on desktop */column-gap & column-rule
column-gap은 단 사이 간격을 설정합니다(이제 flexbox와 grid에서도 사용). column-rule은 간격에 세로 구분선을 그립니다 — border의 단 버전으로 같은 축약형을 씁니다. 구분선은 추가 너비를 차지하지 않고 간격 중앙에 놓입니다. 거슬리지 않게 단을 구분하려면 미묘한 색을 쓰세요.
.article {
column-count: 3;
column-gap: 30px; /* space between columns */
/* divider line (like border) */
column-rule: 1px solid #ddd; /* shorthand */
column-rule-width: 1px;
column-rule-style: solid;
column-rule-color: #ddd;
}
/* rule sits in the gap, doesn't add width */column-span
column-span: all은 요소가 모든 단을 가로지르게 합니다 — 위아래로 단이 흐르는 잡지식 전체 너비 헤드라인에 완벽합니다. column-span: none(기본값)은 콘텐츠가 단을 통과해 흐르게 합니다. 큰 리플로우를 유발할 수 있고 지원이 일관적이지 않았으니 철저히 테스트하세요. 단 블록 사이의 헤딩에 가장 안정적입니다.
.article {
column-count: 3;
}
/* heading spans all columns (like a magazine) */
.article h2 {
column-span: all;
/* resets above the heading, columns resume below */
}
/* default: content flows through columns */
.normal { column-span: none; }
/* note: column-span: all can cause reflow and is
not supported in older Firefox */break-inside & 단 나누기
다단 콘텐츠에서 요소가 단을 가르며 어색하게 잘릴 수 있습니다. break-inside: avoid는 요소(카드, 그림 등)를 한 단 안에서 온전히 유지합니다. break-before/break-after: column은 단 나누기를 강제합니다. 구형 page-break-* 속성은 별칭으로 동작합니다. display: inline-block + width: 100% 핵이 흔했지만, break-inside: avoid가 현대적이고 올바른 방법입니다.
/* prevent an element from splitting across columns */
.card {
break-inside: avoid; /* modern */
-webkit-column-break-inside: avoid; /* old webkit */
page-break-inside: avoid; /* old */
display: inline-block; /* hack for older browsers */
width: 100%;
}
/* control where columns break */
h2 { break-after: column; } /* force new column after */
h3 { break-before: column; } /* force new column before */
p { break-inside: avoid; } /* keep paragraph together */column-fill & 균형
column-fill은 콘텐츠가 단에 분배되는 방식을 제어합니다. balance(기본값)는 높이를 균등화해 단이 대략 같은 지점에서 끝나게 합니다 — 시각적으로 깔끔합니다. auto는 고정 높이가 필요하며 첫 단을 완전히 채운 뒤 다음으로 넘어갑니다 — 인쇄 동작과 같습니다. 일반적으로 균형 잡힌 단이 좋고, 콘텐츠가 엄격히 위→아래로 흐르게 하려면 auto가 좋습니다.
.article {
column-count: 3;
/* balance: equalize column heights (default in most browsers) */
column-fill: balance;
/* auto: fill first column fully, then next (needs height) */
column-fill: auto;
height: 500px; /* required for auto */
}
/* balanced columns look neat but can split awkwardly;
auto is more like print, fills top-to-bottom */사용자 인터페이스
아웃라인 & 접근성
보이는 포커스 표시기는 접근성 요구 사항입니다. :focus-visible은 키보드 사용자에게만(마우스는 제외) 아웃라인을 보여줍니다 — 포커스 스타일링의 모범 사례입니다. 대체물(박스 섀도 링 등) 없이 outline: none을 설정하지 마세요. outline-offset은 요소와 아웃라인 사이에 여유를 줍니다. 모던 브라우저는 border-radius가 아웃라인 모양에 반영된 둥근 아웃라인을 지원합니다.
/* visible focus ring for keyboard users */
button:focus-visible {
outline: 2px solid #0066cc;
outline-offset: 2px;
}
/* never outline: none without a replacement */
/* custom focus ring via box-shadow */
button:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(0, 102, 204, 0.5);
}
/* outline shorthand */
.outlined { outline: 2px dashed red; outline-offset: 4px; }
/* thick rounded outline (modern browsers) */
button:focus-visible {
outline: 3px solid blue;
outline-offset: 2px;
border-radius: 4px;
}resize
resize는 사용자가 요소를 드래그해 크기 조절할 수 있는지 제어합니다. textarea는 기본적으로 리사이즈 가능하며, resize: none으로 비활성화합니다. vertical/horizontal/both는 방향을 제한합니다. 리사이즈가 동작하려면 overflow가 visible이 아니어야 합니다(overflow: auto 또는 hidden 설정). 텍스트에어리어, 코드 에디터, 사용자 조절 패널에 유용합니다.
textarea {
/* allow vertical resize only (default for textarea) */
resize: vertical;
/* allow both axes */
resize: both;
/* horizontal only */
resize: horizontal;
/* disable resizing */
.locked { resize: none; }
/* default: inline/block elements can't be resized;
textarea default is both in most browsers */
}
/* note: resize only works on overflow != visible */caret-color & user-select
caret-color는 편집 가능한 요소의 깜빡이는 커서 색을 설정합니다 — 브랜드 폼에 작지만 좋은 손길입니다. user-select는 텍스트 선택 가능 여부를 제어합니다: none은 비활성화(UI 컨트롤용), all은 클릭 시 요소 전체 선택(코드 블록, 이메일에 좋음), contain은 선택을 요소 안으로 유지합니다. body에 user-select: none은 접근성을 해치므로 피하세요.
/* color of the text cursor in inputs */
input, textarea {
caret-color: #0066cc; /* default: current color */
}
/* custom thick caret (limited support) */
input { caret-color: red; }
/* control text selection by the user */
.no-select { user-select: none; } /* disable selection */
.select-all { user-select: all; } /* select whole element on click */
.select-text { user-select: text; } /* normal text selection */
.select-contain { user-select: contain; } /* selection stays within */
/* email addresses, code blocks often user-select: all */appearance & 폼 스타일링
appearance: none은 폼 컨트롤의 네이티브 OS 스타일을 제거해 CSS로 완전히 스타일링하게 합니다 — 크로스 브라우저 폼 디자인에 필수입니다. select의 네이티브 화살표를 제거한 뒤 커스텀 background-image를 추가하세요. 커스텀 체크박스는 appearance: none과 :checked로 상태를 다룹니다. 완전한 지원을 위해 -webkit-/-moz- 접두사를 붙이고 브라우저별로 철저히 테스트하세요 — 일부 컨트롤(date, color)은 완전한 재스타일링이 여전히 어렵습니다.
/* remove native widget styling */
input, select, button {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
/* custom select arrow (after removing native) */
select {
background-image: url("arrow.svg");
background-repeat: no-repeat;
background-position: right 10px center;
padding-right: 30px;
}
/* style checkbox/radio with appearance: none */
input[type="checkbox"] {
appearance: none;
width: 20px; height: 20px;
border: 2px solid #999;
border-radius: 4px;
}
input[type="checkbox"]:checked {
background: var(--primary);
border-color: var(--primary);
}scroll-behavior & 스크롤바
<html>의 scroll-behavior: smooth는 앵커 링크 클릭 시 점프 대신 부드럽게 스크롤합니다 — 민감한 사용자를 위해 prefers-reduced-motion으로 비활성화를 짝지으세요. 커스텀 스크롤바: 표준 scrollbar-width/scrollbar-color 속성은 Firefox와 현대 Chrome에서 동작하고, ::-webkit-scrollbar 의사 요소는 WebKit/Blink에서 더 세밀한 제어를 제공합니다. 은은한 커스텀 스크롤바는 스크롤 영역의 UX를 다듬어 줍니다.
/* smooth scrolling for anchor links */
html { scroll-behavior: smooth; }
/* respect reduced motion */
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
}
/* custom scrollbar (WebKit) */
.scroll-area::-webkit-scrollbar { width: 8px; }
.scroll-area::-webkit-scrollbar-track { background: #f1f1f1; }
.scroll-area::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; }
.scroll-area::-webkit-scrollbar-thumb:hover { background: #555; }
/* standard scrollbar-color (Firefox + spec) */
.scroll-area {
scrollbar-width: thin;
scrollbar-color: #888 #f1f1f1;
}심화 & 모던 기능
스크롤 스냅
Scroll Snap은 JavaScript 없이 캐러셀이나 전체 페이지 스크롤을 만듭니다. scroll-snap-type: x/y + mandatory/proximity가 축과 엄격함을 제어합니다. scroll-snap-align을 가진 자식은 start/center/end에 스냅됩니다. mandatory는 강제 스냅(전체 페이지 섹션에 좋음), proximity는 가까울 때만 스냅합니다(이미지 갤러리에 부드럽게). sticky 헤더 아래 스냅 지점 오프셋에는 scroll-margin을 결합하세요.
.gallery {
scroll-snap-type: x mandatory; /* snap horizontally, must snap */
overflow-x: auto;
display: flex;
}
.gallery > img {
scroll-snap-align: center; /* start | center | end */
scroll-snap-stop: always; /* can't skip snaps */
flex: 0 0 80%;
}
/* vertical full-page snap */
.pages {
scroll-snap-type: y mandatory;
height: 100vh;
overflow-y: scroll;
}
.page { scroll-snap-align: start; height: 100vh; }
/* proximity: only snaps when close (gentler) */
.soft { scroll-snap-type: y proximity; }object-fit & object-position
object-fit은 <img>나 <video>가 박스를 채우는 방식을 제어합니다 — background-size의 미디어 버전입니다. cover는 박스를 채우고 넘치는 부분을 자르고, contain은 빈 공간이 생기더라도 전체를 맞추며, fill은 늘려서(왜곡) 채웁니다. object-position은 초점을 설정합니다 — cover가 이미지의 중요 부분을 자를 때 유용합니다. 반응형 미디어에 background-image 핵이 필요 없어집니다.
/* cover: fill box, crop overflow (like background-size: cover) */
.avatar img {
width: 100px; height: 100px;
object-fit: cover; /* cover | contain | fill | none | scale-down */
object-position: center; /* position the focal point */
border-radius: 50%;
}
/* contain: whole image visible, may letterbox */
.preview img {
width: 300px; height: 200px;
object-fit: contain;
background: #eee;
}
/* object-position shifts the visible area */
.banner img {
width: 100%; height: 300px;
object-fit: cover;
object-position: top; /* show top of image */
}will-change
will-change는 어떤 속성이 곧 변할지 브라우저에 힌트해 GPU 레이어를 미리 할당하고 최적화하게 합니다. 애니메이션 직전에 적용하고 끝나면 제거하세요 — 많은 요소에 영구 적용하면 메모리를 낭비하고 성능을 해칩니다. 실제로 애니메이션될 속성만(transform, opacity, filter) 나열하세요. 남용하면 의도와 반대 결과가 나오니 아껴서, 의도 있게 사용하세요.
/* hint that an element will animate transform */
.card { will-change: transform; }
/* remove when not needed (frees GPU memory) */
.card.idle { will-change: auto; }
/* multiple properties */
.complex { will-change: transform, opacity; }
/* AVOID: permanent will-change on many elements */
/* .all { will-change: transform, opacity, top, left; } */ /* bad */
/* apply just before animation, remove after */
.prepare { will-change: transform; }
/* JS: el.classList.add('prepare');
setTimeout(() => el.classList.remove('prepare'), 1000); */contain
contain은 요소가 페이지 나머지와 독립적임을 브라우저에 알려 큰 성능 최적화를 가능하게 합니다 — 포함된 요소 내부의 변화가 바깥 재계산을 유발하지 않습니다. layout, paint, style, size가 격리 타입입니다. strict(네 가지 모두, size 포함)가 가장 강력합니다. 반복되는 위젯, 리스트 아이템, 광고에 contain을 적용해 리플로우/리페인트 비용을 제한하세요. size는 명시적 크기가 필요합니다.
/* isolate an element's layout/paint/style from the rest */
.widget {
contain: layout paint style; /* or: strict, content */
/* size: the element's size is independent of its children */
contain: size; /* needs explicit dimensions */
}
/* layout: changes inside don't affect outside layout */
/* paint: children don't render outside the box (clipped) */
/* style: counters and quotes are scoped */
/* size: element ignores children for sizing */
/* full isolation */
.isolated { contain: strict; } /* = size layout paint style */
.content-isolated { contain: content; } /* = layout paint style */
/* useful for performance on complex widgets, lists, ads */aspect-ratio & 보편적 gap
aspect-ratio는 모든 요소에서 width:height 비율을 유지해 미디어 로딩 시 레이아웃 시프트를 막습니다. gap(및 개별 속성 row-gap/column-gap)은 현대적인 간격 도구로, flexbox, grid, 다단 모두에서 동작합니다 — .item + margin + :last-child 핵을 없앱니다. 두 기능 모두 모던 브라우저에서 보편 지원되며, 함께 미디어 비율 유지와 깔끔한 아이템 간격이라는 가장 흔한 CSS 고통 두 가지를 해결합니다.
/* aspect-ratio works on any element */
.video-wrap {
aspect-ratio: 16 / 9;
background: black;
}
/* gap works in flex, grid, and multi-column */
.flex { display: flex; gap: 16px; }
.grid { display: grid; gap: 16px; }
.cols { column-count: 3; column-gap: 16px; }
/* row-gap / column-gap longhands */
.layout {
display: grid;
row-gap: 24px;
column-gap: 16px;
}
/* gap replaced margin-based spacing hacks */
/* (no more .item:last-child { margin-right: 0 }) */관련 CSS3 스니펫
Copy-paste ready code for common tasks.
Flexbox Layout
Align and distribute items along one axis with flexbox.
Grid Layout
Build two-dimensional layouts with grid-template-areas.
Animations
Define keyframes and apply reusable animations.
Transitions
Smoothly interpolate properties on state change.
2D & 3D Transforms
Translate, rotate, and scale elements with GPU-friendly transforms.
Media Queries
Apply responsive, print, and preference-based styles.
Custom Properties
Define and reuse CSS variables with live updates.
Pseudo-Classes
Select elements by state and structural position.
Was this helpful?