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

CSS min-width 속성 완벽 가이드 – 요소의 최소 너비 설정 방법

CSS의 min-width 속성은 요소의 콘텐츠 박스(content box)에 고정된 최소 너비를 지정할 때 사용합니다. 이 속성이 적용되면 요소의 너비가 아무리 작게 설정되더라도 콘텐츠 박스는 min-width로 지정한 값보다 좁아지지 않습니다.

문법(Syntax)

CSS min-width 속성의 기본 문법은 다음과 같습니다.

Selector {
   min-width: /*value*/
}

예제 1

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 min-width 속성 완벽 가이드 – 요소의 최소 너비 설정 방법

'Set minWidth' 버튼 클릭 후 −

CSS min-width 속성 완벽 가이드 – 요소의 최소 너비 설정 방법

예제 2

이번에는 여러 요소에 한 번에 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(62deg, #fbab7e 0%, #f7ce68 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">
Lorem Text
</div>
<div class="contentDiv">
This is paragraph 3 with some dummy text.
</div>
<button onclick="add()" class="btn">Set minWidth</button>
</div>
<script>
function add() {
   var all = document.querySelectorAll('.contentDiv');
   for(var i=0; i<all.length; i++)
   all[i].style.minWidth = "100%";
}
</script>
</body>
</html>

실행 결과

위 코드의 실행 결과는 다음과 같습니다.

'Set minWidth' 버튼 클릭 전 −

CSS min-width 속성 완벽 가이드 – 요소의 최소 너비 설정 방법

'Set minWidth' 버튼 클릭 후 −

CSS min-width 속성 완벽 가이드 – 요소의 최소 너비 설정 방법