CSS의 @media 규칙은 하나의 스타일시트 안에서 인쇄(print), 화면(screen), 전체(all) 등 서로 다른 미디어 유형에 맞춰 각각 다른 스타일을 적용할 수 있게 해주는 강력한 기능입니다. 반응형 웹 디자인의 핵심 요소로, 미디어 유형 목록과 해당 미디어에 적용할 CSS 선언 블록을 함께 작성합니다.
기본 문법
@media 규칙의 기본 문법은 다음과 같습니다.
@media not | only mediatype and (표현식) {
CSS 코드;
}여기서 not이나 only는 선택적으로 사용할 수 있으며, and 뒤에는 화면 너비(max-width, min-width 등)와 같은 조건식을 괄호 안에 작성합니다. 조건이 참일 때 중괄호 안의 CSS 코드가 적용됩니다.
예제 1: 화면 너비에 따라 레이아웃과 배경색 변경하기
아래 예제는 화면 크기에 따라 컬럼의 너비와 페이지 배경색이 달라지도록 @media 규칙을 활용한 사례입니다.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
box-sizing: border-box;
}
.col {
float: left;
width: 20%;
padding: 40px;
}
body {
background-color: lemonchiffon;
margin: 20px;
}
@media screen and (max-width: 850px) {
.col {
width: 50%;
}
body {
background-color: mediumseagreen;
}
}
@media screen and (max-width: 550px) {
.col {
width: 100%;
}
body {
background-color: powderblue;
}
}
</style>
</head>
<body>
<div class="row">
<div class="col" style="background-color:#373;"> </div>
<div class="col" style="background-color:#363;"> </div>
<div class="col" style="background-color:#353;"> </div>
<div class="col" style="background-color:#343;"> </div>
<div class="col" style="background-color:#333;"> </div>
</div>
</body>
</html>실행 결과
위 코드를 실행하면 화면 크기에 따라 다음과 같이 표시됩니다.
화면 너비가 850px보다 클 때: 5개의 컬럼이 한 줄에 나란히 배치되고 배경색은 연노랑(lemonchiffon)으로 표시됩니다.
화면 너비가 550px~850px 사이일 때: 컬럼이 한 줄에 2개씩 배치되고 배경색은 청록색(mediumseagreen)으로 변경됩니다.
화면 너비가 550px보다 작을 때: 모든 컬럼이 세로로 쌓이며(너비 100%) 배경색은 연한 파란색(powderblue)으로 바뀝니다.
예제 2: 화면 크기에 따라 배경 이미지와 글자색 변경하기
이번 예제는 화면 크기 조건에 따라 단락(p) 요소의 배경 이미지와 글자 색상을 다르게 적용하는 방법을 보여줍니다.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
background-origin: content-box;
background-repeat: no-repeat;
background-size: cover;
box-shadow: 0 0 3px black;
padding: 20px;
background-origin: border-box;
}
@media screen and (max-width: 900px) {
p{
background: url("https://www.tutorialspoint.com/swing/images/swing.jpg");
color: #c303c3;
}
}
@media screen and (max-width: 500px) {
p {
color: black;
background: url("https://www.tutorialspoint.com/cplusplus/images/cplusplus.jpg");
}
}
</style>
</head>
<body>
<p>This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. This is demo text. This is demo text. This is demo text.
This is demo text. </p>
</body>
</html>실행 결과
위 코드를 실행하면 화면 크기에 따라 다음과 같이 표시됩니다.
화면 너비가 500px보다 클 때: 기본 스타일 또는 swing 관련 배경 이미지가 적용되고, 900px 이하에서는 보라색 계열(#c303c3)의 글자색이 나타납니다.
화면 너비가 500px보다 작을 때: C++ 관련 배경 이미지로 교체되고 글자색은 검정(black)으로 변경됩니다.
정리
@media 규칙을 활용하면 별도의 자바스크립트 없이 순수 CSS만으로 기기나 화면 크기에 대응하는 반응형 웹페이지를 만들 수 있습니다. 데스크톱, 태블릿, 모바일 등 다양한 환경에서 최적화된 사용자 경험을 제공하고 싶다면 max-width, min-width 같은 미디어 특성 조건을 적극적으로 활용해 보세요.