너비가 max-width보다 크더라도 요소의 콘텐츠 상자가 더 넓어지는 것을 허용하지 않는 CSS max-width 속성을 사용하여 요소의 콘텐츠 상자에 대해 고정된 최대 너비를 정의할 수 있습니다.
구문
CSS max-width 속성의 구문은 다음과 같습니다 -
Selector {
max-width: /*value*/
} CSS max-width 속성의 예를 살펴보겠습니다 -
예시
<!DOCTYPE html>
<html>
<head>
<title>CSS max-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{
max-width:200px;
overflow: hidden;
}
</style>
<body>
<div id="containerDiv">
<div id="contentDiv">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
</div>
<button onclick="add()" class="btn">Set maxWidth</button>
</div>
<script>
function add() {
document.querySelector('#contentDiv').style.maxWidth = "100%";
}
</script>
</body>
</html> 출력
'최대 너비 설정'을 클릭하기 전에 버튼 -

'최대 너비 설정'을 클릭한 후 버튼 -

CSS max-width 속성에 대한 또 다른 예를 살펴보겠습니다. -
예시
<!DOCTYPE html>
<html>
<head>
<title>CSS max-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;
}
#contentDiv1, #contentDiv2{
width:100%;
border: 1px solid black;
margin: 0 auto;
}
#contentDiv2{
width: 80%;
}
</style>
<body>
<div id="containerDiv">
<div id="contentDiv1">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text.
</div>
<div id="contentDiv2">
This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy text. This is paragraph 1 with some dummy.
</div>
<button onclick="add()" class="btn">Set maxWidth</button>
</div>
<script>
function add() {
document.querySelector('#contentDiv1').style.maxWidth = "80%";
}
</script></body></html> 출력
'최대 너비 설정'을 클릭하기 전에 버튼 -

'최대 너비 설정'을 클릭한 후 버튼 -
