개요
크기 인식 스타일 지정을 사용하면 구성요소가 전체 화면 크기가 아닌 사용 가능한 공간에 따라 레이아웃이나 모양을 변경할 수 있습니다. 이는 레이아웃의 여러 부분 (예: 좁은 사이드바 또는 넓은 기본 영역)에 배치될 수 있는 카드나 탐색 메뉴와 같은 구성요소에 유용합니다.
컨테이너 쿼리를 사용하면 구성요소를 진정한 모듈식으로 만들 수 있으므로 사용하는 것이 좋습니다. 구성요소가 어디에 위치할지 알 필요가 없으며 가능한 모든 레이아웃을 처리하기 위해 복잡한 미디어 쿼리를 작성할 필요도 없습니다.
구현
1. 컨테이너 정의
필수: 먼저 브라우저에 측정할 컨테이너 요소를 알려야 합니다.
.card-container {
/* Define the container type. Use 'inline-size' for width-based queries. */
/* You can also use 'size' for both width and height, but it requires explicit sizing. */
container-type: inline-size;
}
2. 컨테이너 크기에 따라 스타일 적용
@container 규칙을 사용하여 컨테이너가 특정 크기에 도달할 때 스타일을 적용합니다.
/* Default styles for small containers (stacked layout) */
.card {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Styles for larger containers (side-by-side layout) */
/* This triggers when the container is wider than 400px */
@container (min-width: 400px) {
.card {
flex-direction: row;
align-items: center;
}
.card-image {
width: 150px;
height: 150px;
}
}
3. 조건부로 콘텐츠 표시
컨테이너 쿼리를 사용하여 공간이 더 있을 때 추가 세부정보를 숨기거나 표시할 수도 있습니다.
.card-details {
/* Hide extra details by default in small spaces */
display: none;
}
@container (min-width: 600px) {
.card-details {
/* Show details when there is plenty of room */
display: block;
}
}
대체 전략
컨테이너 쿼리를 지원하지 않는 브라우저의 경우 가장 좋은 방법은 안전한 기본 레이아웃 (예: 누적된 세로 레이아웃)을 사용하고 일반 화면 크기가 허용하는 경우 미디어 쿼리를 사용하여 점진적으로 개선하는 것입니다.
/* Default safe stacked layout */
.card {
display: flex;
flex-direction: column;
}
/* Fallback using media queries for older browsers */
@media (min-width: 600px) {
.card {
flex-direction: row;
}
}
/* Overwrite with container queries where supported */
@supports (container-type: inline-size) {
@media (min-width: 600px) {
.card {
/* Reset media query fallback if needed, or let container query handle it */
flex-direction: column;
}
}
@container (min-width: 400px) {
.card {
flex-direction: row;
}
}
}
이렇게 하면 이전 브라우저를 사용하는 사용자도 모든 특정 컨테이너 너비에 완벽하게 맞지 않더라도 사용 가능한 레이아웃을 사용할 수 있습니다.