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

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

คุณสมบัติ min-width ใน CSS ใช้กำหนดความกว้างขั้นต่ำของกล่องเนื้อหา (content box) ไม่ให้องค์ประกอบแคบลงไปกว่าค่านี้ แม้ความกว้างจริงจะน้อยกว่าก็ตาม

ไวยากรณ์ (Syntax)

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

ตัวอย่างที่ 1: กำหนด min-width และเปลี่ยนค่าด้วย JavaScript

<!DOCTYPE html>
<html>
<head>
  <title>CSS min-width Property</title>
  <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>
</head>
<body>
  <div id="containerDiv">
    <div class="contentDiv">Paragraph 1</div>
    <div class="contentDiv">Paragraph 2</div>
    <div class="contentDiv">Paragraph 3</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:

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

หลังกดปุ่ม Set minWidth (องค์ประกอบที่ 2 ขยายเต็มความกว้าง):

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

ตัวอย่างที่ 2: ใช้ min-width กับหลายองค์ประกอบพร้อมกัน

<!DOCTYPE html>
<html>
<head>
  <title>CSS min-width Property</title>
  <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>
</head>
<body>
  <div id="containerDiv">
    <div class="contentDiv">Paragraph 1</div>
    <div class="contentDiv">Lorem Text</div>
    <div class="contentDiv">Paragraph 3</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>

ผลลัพธ์

ก่อนกดปุ่ม:

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

หลังกดปุ่ม (ทุกองค์ประกอบขยายเต็มความกว้าง):

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

จุดสำคัญ

  • min-width ป้องกันไม่ให้องค์ประกอบแคบลงไปกว่าค่าที่กำหนด
  • ใช้ร่วมกับ max-width เพื่อควบคุมช่วงความกว้างได้
  • เหมาะสำหรับ Responsive Design ป้องกันเนื้อหาอ่านยากบนหน้าจอแคบ