Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

คุณสมบัติ max-width ใน CSS


เราสามารถกำหนด max-width คงที่สำหรับกล่องเนื้อหาขององค์ประกอบโดยใช้คุณสมบัติ max-width ใน CSS ซึ่งไม่ให้กล่องเนื้อหาขององค์ประกอบกว้างกว่านั้น แม้ว่า width จะมากกว่า 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>

ผลลัพธ์

ก่อนคลิกปุ่ม 'Set maxWidth':

คุณสมบัติ max-width ใน CSS

หลังคลิกปุ่ม 'Set maxWidth':

คุณสมบัติ max-width ใน CSS

ลองดูอีกตัวอย่างสำหรับคุณสมบัติ 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>

ผลลัพธ์

ก่อนคลิกปุ่ม 'Set maxWidth':

คุณสมบัติ max-width ใน CSS

หลังคลิกปุ่ม 'Set maxWidth':

คุณสมบัติ max-width ใน CSS