Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS 절대 단위와 상대 단위 완벽 가이드

CSS에서 사용하는 절대 단위(Absolute Units)상대 단위(Relative Units)는 모두 '거리(Distance)' 단위 범주에 속합니다. 두 단위의 가장 큰 차이는 기준점입니다. 절대 단위는 화면이나 출력 환경과 무관하게 고정된 물리적 값을 가지는 반면, 상대 단위는 다른 요소나 뷰포트를 기준으로 길이가 결정됩니다.

CSS 상대 단위(Relative Units)

상대 단위는 특정 요소의 길이를 다른 요소 또는 뷰포트를 기준으로 정의합니다. 예를 들어 vh 단위는 뷰포트(viewport)의 높이를 기준으로 값이 계산됩니다. 반응형 웹 디자인에서 필수적으로 활용되는 단위들입니다.

주요 상대 단위 목록

번호단위 및 기준
1%
부모 요소의 크기를 기준으로 함
2em
해당 요소의 글꼴 크기를 기준으로 함
3ex
요소 글꼴의 x-height(소문자 x의 높이)를 기준으로 함
4lh
해당 요소의 줄 높이(line-height)를 기준으로 함
5rem
루트(root) 요소의 글꼴 크기를 기준으로 함
6rlh
루트 요소의 줄 높이를 기준으로 함
7vb
루트 요소의 블록 축(block axis) 방향 뷰포트 크기의 1%
8vh
뷰포트 높이의 1%
9vmax
뷰포트에서 더 큰 쪽 치수의 1%
10vmin
뷰포트에서 더 작은 쪽 치수의 1%
11vw
뷰포트 너비의 1%

상대 단위 실습 예제

아래 예제는 라디오 버튼으로 단위를 선택하고, 입력한 숫자와 텍스트를 바탕으로 글꼴 크기가 어떻게 달라지는지 확인할 수 있는 데모입니다.

<!DOCTYPE html>
<html>
<head>
<title>CSS 상대 단위</title>
<style>
html {
    font-size: 14px;
    line-height: normal;
}
form {
    width: 70%;
    margin: 0 auto;
    text-align: center;
}
* {
    padding: 2px;
    margin: 5px;
}
input[type="button"] {
    border-radius: 10px;
}
#textContain {
    font-size: 20px;
    line-height: 2;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-상대-단위</legend>
<input type="text" id="textSelect" placeholder="여기에 텍스트를 입력하세요...">
<input type="number" id="numSelect" value="1" min="1">
<div id="radioBut">
<input class="radio" type="radio" name="heading" value="em" checked><label>em</label>
<input class="radio" type="radio" name="heading" value="rem"><label>rem</label>
<input class="radio" type="radio" name="heading" value="vw"><label>vw</label>
<input class="radio" type="radio" name="heading" value="vh"><label>lh</label>
<input class="radio" type="radio" name="heading" value="ex"><label>ex</label>
</div>
<div id="textContain">텍스트 미리보기: <span id="textPreview">출력 결과가 여기에 표시됩니다</span></div>
<input type="button" onclick="changeText()" value="미리보기">
</fieldset>
</form>
<script>
var textSelect = document.getElementById("textSelect");
var numSelect = document.getElementById("numSelect");
var textPreview = document.getElementById("textPreview");
function changeText() {
    if(textSelect.value === '')
        textPreview.textContent = '먼저 텍스트를 입력하세요';
    else {
        for(var i=0; i<5; i++){
            var radInp = document.getElementsByClassName('radio')[i];
            if(radInp.checked === true){
                textPreview.textContent = textSelect.value;
                textPreview.style.fontSize = numSelect.value + radInp.value;
            }
        }
    }
}
</script>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.

버튼을 클릭하기 전:

CSS 절대 단위와 상대 단위 완벽 가이드

'em' 옵션 선택 후 빈 텍스트 필드로 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

'rem' 옵션 선택 후 텍스트를 입력하고 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

'em' 옵션 선택 후 텍스트를 입력하고 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

CSS 절대 단위(Absolute Units)

절대 단위는 브라우저 환경이나 다른 요소에 영향을 받지 않고 항상 고정된 값을 유지합니다. 인쇄물처럼 정확한 물리적 크기가 필요한 경우에 유용하지만, 화면 크기가 다양한 웹 환경에서는 상대 단위보다 유연성이 떨어집니다.

주요 절대 단위 목록

번호단위 및 설명
1cm
센티미터 (1cm = 100mm)
2in
인치 (1in = 2.54cm)
3mm
밀리미터
4pc
파이카 (1pc = 12pt)
5pt
포인트 (1pt = 1/72in)
6px
픽셀 (1px = 0.75pt)

절대 단위 실습 예제

아래 예제는 px, pt, pc, in, cm 단위를 선택하여 텍스트 크기 변화를 비교해 볼 수 있는 데모입니다.

<!DOCTYPE html>
<html>
<head>
<title>CSS 절대 단위</title>
<style>
form {
    width: 70%;
    margin: 0 auto;
    text-align: center;
}
* {
    padding: 2px;
    margin: 5px;
}
input[type="button"] {
    border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-절대-단위</legend>
<input type="text" id="textSelect" placeholder="여기에 텍스트를 입력하세요...">
<input type="number" id="numSelect" value="10" min="1">
<div id="radioBut">
<input class="radio" type="radio" name="heading" value="pc"><label>pc</label>
<input class="radio" type="radio" name="heading" value="pt"><label>pt</label>
<input class="radio" type="radio" name="heading" value="px" checked><label>px</label>
<input class="radio" type="radio" name="heading" value="in"><label>in</label>
<input class="radio" type="radio" name="heading" value="cm"><label>cm</label>
</div>
<div id="textContain">텍스트 미리보기: <span id="textPreview">출력 결과가 여기에 표시됩니다</span></div>
<input type="button" onclick="changeText()" value="미리보기">
</fieldset>
</form>
<script>
var textSelect = document.getElementById("textSelect");
var numSelect = document.getElementById("numSelect");
var textPreview = document.getElementById("textPreview");
function changeText() {
    if(textSelect.value === '')
        textPreview.textContent = '먼저 텍스트를 입력하세요';
    else {
        for(var i=0; i<5; i++){
            var radInp = document.getElementsByClassName('radio')[i];
            if(radInp.checked === true){
                textPreview.textContent = textSelect.value;
                textPreview.style.fontSize = numSelect.value + radInp.value;
            }
        }
    }
}
</script>
</body>
</html>

실행 결과

위 코드를 실행하면 다음과 같은 결과를 확인할 수 있습니다.

버튼을 클릭하기 전:

CSS 절대 단위와 상대 단위 완벽 가이드

'px' 옵션 선택 후 텍스트를 입력하고 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

'pt' 옵션 선택 후 텍스트를 입력하고 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

'pc' 옵션 선택 후 텍스트를 입력하고 '미리보기' 버튼을 클릭한 경우:

CSS 절대 단위와 상대 단위 완벽 가이드

정리: 어떤 단위를 사용해야 할까?

일반적으로 웹 페이지 전체의 일관된 타이포그래피를 위해서는 rem, 부모 요소에 비례하는 레이아웃에는 %, 화면 크기에 대응하는 반응형 디자인에는 vw/vh 계열 단위를 권장합니다. 반면 인쇄 스타일시트(@media print)처럼 물리적 크기가 중요한 경우에는 pt, cm, mm 같은 절대 단위가 적합합니다. 두 단위 그룹의 특성을 이해하고 상황에 맞게 조합하면 더욱 견고하고 유연한 CSS를 작성할 수 있습니다.