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

CSS 차원 속성 완벽 가이드: width, height, min·max 속성 활용법

CSS 차원 속성이란?

CSS에는 width, height, max-height 등 여러 가지 차원(dimension) 속성이 있으며, 이를 활용하면 요소 콘텐츠 박스(content box)의 크기를 자유롭게 제어할 수 있습니다.

차원 속성은 반응형 웹 디자인에서 특히 중요합니다. 고정된 픽셀(px) 값 대신 퍼센트(%)나 뷰포트 단위(vw, vh)를 함께 사용하면 다양한 화면 크기에 유연하게 대응하는 레이아웃을 만들 수 있습니다.

주요 차원 속성 정리

  • height / width — 요소의 기본 높이와 너비를 지정합니다.
  • min-height / min-width — 요소가 가질 수 있는 최소 크기를 지정합니다. 콘텐츠가 아무리 줄어들어도 이 값보다 작아지지 않습니다.
  • max-height / max-width — 요소가 가질 수 있는 최대 크기를 지정합니다. 콘텐츠가 아무리 늘어나도 이 값을 초과하지 않습니다.

예제 1: max-height 속성 사용하기

다음 예제는 이미지 컨테이너에 max-height를 적용하여 요소의 최대 높이를 제한하는 방법을 보여줍니다.

<!DOCTYPE html>
<html>
<head>
<title>CSS max-height</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
#containerDiv {
   margin: 0 auto;
   max-height: 150px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS max-height</legend>
<div id="containerDiv">
<img id="image" src="https://www.tutorialspoint.com/machine_learning_with_python/images/machine-learning-with-python-mini-logo.jpg">
</div>
</fieldset>
</form>
</body>
</html>

실행 결과

max-height 적용 전:

CSS 차원 속성 완벽 가이드: width, height, min·max 속성 활용법

max-height 적용 후:

CSS 차원 속성 완벽 가이드: width, height, min·max 속성 활용법

위 결과에서 확인할 수 있듯이, max-height: 150px;가 적용되면 컨테이너의 높이가 150px를 넘지 않도록 제한됩니다. 이미지처럼 크기가 변할 수 있는 콘텐츠의 영역을 일정하게 유지하고 싶을 때 유용합니다.

예제 2: min-width 속성 사용하기

다음은 JavaScript와 함께 min-width 속성을 동적으로 변경하는 예제입니다. 버튼을 클릭하면 특정 요소의 최소 너비가 실시간으로 조정됩니다.

<!DOCTYPE html>
<html>
<head>
<title>CSS min-width Property</title>
</head>
<style>
* {
   padding: 2px;
   margin:5px;
}
button {
   border-radius: 10px;
}
#containerDiv {
   width:70%;
   margin: 0 auto;
   padding:20px;
   background-image: linear-gradient(135deg, #dc3545 0%, #9599E2 100%);
   text-align: center;
   border-radius: 10px;
}
.contentDiv{
   min-width:200px;
   border: 1px solid black;
}
</style>
<body>
<div id="containerDiv">
<div class="contentDiv">
This is paragraph 1 with some dummy text.
</div>
<div class="contentDiv">
This is paragraph 2 with some dummy text.
</div>
<div class="contentDiv">
This is paragraph 2 with some dummy text.
</div>
<button onclick="add()" class="btn">Set minWidth</button>
</div>
<script>
function add() {
   document.querySelectorAll('.contentDiv')[1].style.minWidth = "100%";
}
</script>
</body>
</html>

실행 결과

'Set minWidth' 버튼 클릭 전:

CSS 차원 속성 완벽 가이드: width, height, min·max 속성 활용법

'Set minWidth' 버튼 클릭 후:

CSS 차원 속성 완벽 가이드: width, height, min·max 속성 활용법

버튼을 클릭하면 두 번째 콘텐츠 div에 min-width: 100%가 적용되어 부모 요소의 전체 너비를 확보하게 됩니다. 이처럼 min-width는 콘텐츠가 좁아지더라도 최소한의 가독성 있는 너비를 보장해야 할 때 활용할 수 있습니다.