JavaScript / screen으로 화면 크기 구하기와 뷰포트 차이
window.screen은 현재 브라우저 창이 표시되는 화면의 크기와 사용 가능 영역, 색 깊이 정보를 담은 Screen 객체입니다. 페이지가 실제로 배치되는 브라우저 안쪽 영역의 너비를 구하려면 window.innerWidth를 사용해야 합니다. 화면 크기와 뷰포트 크기는 서로 다른 값입니다.
Screen 객체의 주요 속성
window.screen 또는 짧게 screen으로 접근합니다. 각 속성은 읽기 전용이며 브라우저가 보고하는 값을 반환합니다.
| 속성 | 의미 |
|---|---|
width, height |
화면의 가로·세로 크기 |
availWidth, availHeight |
운영체제의 고정 UI 등을 제외하고 창에 사용 가능한 크기 |
colorDepth, pixelDepth |
브라우저가 보고하는 색 깊이(비트) |
작업 표시줄의 위치와 운영체제 설정에 따라 사용 가능 영역의 차이는 달라집니다. 특정 픽셀 수를 기대하지 마세요. MDN의 Screen 객체 문서에 각 속성의 정의가 있습니다.
화면 크기와 뷰포트 크기 비교
화면 전체 크기인 screen.width는 브라우저 창의 콘텐츠 영역 너비가 아닙니다. 창을 줄여도 화면 크기 자체는 그대로일 수 있지만 window.innerWidth는 현재 레이아웃 뷰포트의 너비를 나타냅니다. 반응형 화면의 분기에는 CSS 미디어 쿼리를 우선하고, JavaScript에서 현재 뷰포트가 필요할 때 innerWidth나 matchMedia()를 사용하세요.
console.log(screen.width); // 화면의 너비: 환경마다 다름
console.log(window.innerWidth); // 현재 레이아웃 뷰포트 너비
여러 화면을 사용하는 환경이나 브라우저의 개인정보 보호 설정에 따라 보고되는 값은 달라질 수 있습니다. 같은 기기 모델이라도 값이 같다고 가정하지 마세요. MDN의 window.innerWidth 문서는 뷰포트의 측정 범위를 설명합니다.
전체 예제: 현재 값 비교하기
아래 코드를 screen-info.html에 저장해 브라우저에서 엽니다. 화면 값과 뷰포트 값을 함께 출력합니다. 브라우저 창 크기를 변경하면 resize 이벤트로 값이 다시 표시되고, 버튼을 눌러 직접 다시 읽을 수도 있습니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>화면과 브라우저 창 크기 비교</title>
</head>
<body>
<button id="refresh" type="button">값 다시 읽기</button>
<pre id="result" aria-live="polite"></pre>
<script>
const result = document.querySelector('#result');
function showSizes() {
const values = [
['screen.width', screen.width],
['screen.height', screen.height],
['screen.availWidth', screen.availWidth],
['screen.availHeight', screen.availHeight],
['screen.colorDepth', screen.colorDepth],
['screen.pixelDepth', screen.pixelDepth],
['window.innerWidth', window.innerWidth],
['window.innerHeight', window.innerHeight]
];
result.textContent = values.map(([name, value]) => `${name}: ${value}`).join('\n');
}
document.querySelector('#refresh').addEventListener('click', showSizes);
window.addEventListener('resize', showSizes);
showSizes();
</script>
</body>
</html>
표시되는 숫자는 실행 환경마다 다릅니다. 창 너비를 줄였을 때 window.innerWidth가 줄어드는지, screen.width는 어떻게 보고되는지 비교하세요. availHeight와 height의 차이를 작업 표시줄 높이로 단정하지 마세요. 화면·브라우저 UI 설정에 따라 의미가 달라집니다.




