CSS3의 box-sizing 속성을 활용하면 요소의 크기가 계산되는 방식을 조절할 수 있어 레이아웃 작업이 훨씬 수월해집니다. 특히 border-box와 content-box 값의 차이를 이해하면 패딩이나 테두리로 인해 레이아웃이 깨지는 문제를 효과적으로 방지할 수 있습니다.
box-sizing 속성의 두 가지 방식
border-box : 요소의 너비(width)와 높이(height)에 안쪽 여백(padding)과 테두리(border)가 모두 포함됩니다. 지정한 크기 그대로 유지되므로 반응형 레이아웃에서 널리 사용됩니다.
content-box : CSS의 기본값으로, 너비와 높이가 콘텐츠 영역에만 적용됩니다. 여기에 패딩과 테두리 두께가 더해져 실제 화면상 크기가 커지게 됩니다.
예제 코드
다음은 box-sizing 속성을 사용하여 레이아웃을 구성하는 전체 코드입니다.
<!DOCTYPE html>
<html>
<head>
<style>
body{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.container{
width: 500px;
border:8px solid rgb(35, 0, 100);
}
.border {
box-sizing: border-box;
width: 100%;
height: 100px;
border: 4px solid rgb(4, 97, 54);
}
.content {
width: 100%;
height: 100px;
padding: 50px;
border: 4px solid rgb(255, 0, 191);
box-sizing: content-box;
}
</style>
</head>
<body>
<h1>Box sizing layout example</h1>
<div class="container">
<div class="border">This div has 100% width and box-sizing property set to border
box</div>
<br>
<div class="content">This div also has 100% width but has the box-sizing property set to
content box</div>
</div>
</body>
</html>
코드 설명
위 예제에서 첫 번째 div(.border)는 box-sizing: border-box가 적용되어, 패딩과 테두리가 포함된 상태로도 부모 컨테이너의 100% 너비를 정확히 차지합니다.
반면 두 번째 div(.content)는 box-sizing: content-box가 적용되어 좌우 50px씩의 패딩과 4px 테두리가 추가되면서 실제 렌더링 크기가 부모 컨테이너를 초과하게 됩니다. 이처럼 두 값의 차이를 시각적으로 비교해 볼 수 있습니다.
실행 결과
위 코드를 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.
