6-4. 미디어쿼리
CSS의 미디어 쿼리(Media Queries)는 특정 미디어의 성능과 상황에 따라 특정한 CSS를 적용할 때 사용합니다.
반응형 웹에서는 접속하는 기기(데스크탑, 테블릿, 스마트 폰 등)를 판단하기 위해 뷰포트의 너비를 체크하게 됩니다.
다음 예제에서는 기기의 뷰포트의 최대 너비가 600 픽셀인 경우, 즉 600 픽셀 이하인 경우에는
웹 페이지의 배경 색상을 하늘색(skyblue)으로 변경합니다.
미디어 쿼리로 배경 색상 변경
ex6-5.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, inital-scale=1.0">
<style>
body { background-color: skyblue; }
@media only screen and (max-width: 600px) {
body {
background-color: yellow;
}
}
</style>
</head>
<body>
<p>브라우저의 너비가 600 픽셀 이하에서는 배경 색상이 노란색으로 변경된다.</p>
</body>
</html>
ex6-5.html의 실행 결과
이번에는 미디어 쿼리를 이용하여 데스크탑과 스마트 폰에서 동작하는 반응형 웹 페이지를 만드는 다음의 예제를 살펴봅니다.
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li { list-style-type: none; }
header {
height: 80px;
padding: 30px 0 0 30px;
background-color: #33b30b;
color: #ffffff;
}
.row {
margin-top: 10px;
}
.row::after {
content: "";
clear: both;
display: block;
}
.menu li {
padding: 10px;
margin-bottom: 12px;
background-color: #3ea3d9;
color: #ffffff;
box-shadow: 3px 3px 5px #aaaaaa;
}
.menu a:link, .menu a:visited, .menu a:hover, .menu a:active {
color: #ffffff;
text-decoration: none;
}
.menu li:hover {
background-color: orange;
}
section p {
line-height: 150%;
padding-top: 10px;
}
footer {
height: 80px;
background-color: #eeeeee;
color: #000000;
text-align: center;
font-size: 0.9em;
padding-top: 30px;
margin-top: 10px;
}
/* 데스크 탑 */
.col_1 {width: 8.33%;}
.col_2 {width: 16.66%;}
.col_3 {width: 25%;}
.col_4 {width: 33.33%;}
.col_5 {width: 41.66%;}
.col_6 {width: 50%;}
.col_7 {width: 58.33%;}
.col_8 {width: 66.66%;}
.col_9 {width: 75%;}
.col_10 {width: 83.33%;}
.col_11 {width: 91.66%;}
.col_12 {width: 100%;}
[class*="col_"] {
float: left;
padding: 15px;
}
/* 미디어 쿼리 */
@media only screen and (max-width: 768px) {
/* 스마트 폰 */
[class*="col_"] {
width: 100%;
}
}
</style>
<body>
<header>
<h3>웹 프로그래밍 강좌</h3>
</header>
<div class="row">
<nav class="col_3 menu">
<ul>
<li><a href="#">웹 페이지란?</a></li>
<li><a href="#">HTML/CSS</a></li>
<li><a href="#">PHP 프로그래밍</a></li>
<li><a href="#">자바스크립트/jQuery</a></li>
</ul>
</nav>
<section class="col_9">
<h2>웹 페이지란?</h2>
<p>웹 페이지는 웹 서핑을 할 때 보는 각각의 화면을 말한다. 웹 페이지는 HTML과 CSS로 구성된 HTML 문서와 관련된 이미지, 동영상, 음악 파일 등의 데이터 파일로 구성된다.</p>
<p>웹 브라우저는 웹 서버에서 보내온 웹 페이지에 관련된 파일들을 해석하여 브라우저 화면에 내용을 보여준다.</p>
</section>
</div> <!-- row -->
<footer>
<p>Copyright 2021. (goldmont) all rights reserved.</p>
</footer>
</body>
ex6-6.html의 실행 결과