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

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

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

ไวยากรณ์ (Syntax)

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

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

<!DOCTYPE html>
<html>
<head>
  <title>CSS min-height 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-height: 150px; }
  </style>
</head>
<body>
  <div id="containerDiv">
    <div id="contentDiv">
      This is paragraph 1 with some dummy text. (ซ้ำหลายบรรทัด)
    </div>
    <button onclick="add()" class="btn">Set minHeight</button>
  </div>
  <script>
    function add() {
      document.querySelector('#contentDiv').style.minHeight = "100px";
    }
  </script>
</body>
</html>

ผลลัพธ์

ก่อนกดปุ่ม Set minHeight:

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

หลังกดปุ่ม Set minHeight:

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

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

<!DOCTYPE html>
<html>
<head>
  <title>CSS min-height 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;
    }
    #contentDiv1, #contentDiv2 {
      width: 50%; border: 2px solid black; margin: 0 auto;
    }
  </style>
</head>
<body>
  <div id="containerDiv">
    <div id="contentDiv1">Paragraph 1 (สั้น)</div>
    <div id="contentDiv2">Paragraph 2 (ยาวกว่า)</div>
    <button onclick="add()" class="btn">Set minHeight</button>
  </div>
  <script>
    function add() {
      document.querySelector('#contentDiv1').style.minHeight = "95px";
    }
  </script>
</body>
</html>

ผลลัพธ์

ก่อนกดปุ่ม:

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

หลังกดปุ่ม:

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

จุดสำคัญ

  • min-height ป้องกันไม่ให้องค์ประกอบหดเล็กลงไปกว่าค่าที่กำหนด
  • หากเนื้อหามากกว่า ความสูงจะขยายตามเนื้อหาได้ตามปกติ
  • ใช้ร่วมกับ max-height เพื่อควบคุมช่วงความสูงได้