How to set the maximum height of an element with JavaScript?

Use the maxHeight property in JavaScript to set the maximum height of an element. This property controls how tall an element can grow, with content overflowing when the limit is reached.

Syntax

element.style.maxHeight = "value";

Parameters

The maxHeight property accepts various values:

  • Pixels: "200px"
  • Percentage: "50%" (relative to parent)
  • Keywords: "none" (no limit), "initial", "inherit"

Example: Setting Maximum Height

<!DOCTYPE html>
<html>
<head>
<style>
   #box {
      width: 300px;
      background-color: gray;
      overflow: auto;
   }
</style>
</head>
<body>
<p>Click below to set Maximum height.</p>
<button type="button" onclick="display()">Max Height</button>
<div id="box">
<p>This is a div. This is a div. This is a div.</p>
<p>This is a div. This is a div. This is a div.</p>
<p>This is a div. This is a div. This is a div.</p>
<p>This is a div. This is a div. This is a div.</p>
<p>This is a div. This is a div. This is a div.</p>
</div>
<br>
<script>
   function display() {
      document.getElementById("box").style.maxHeight = "70px";
   }
</script>
</body>
</html>

Multiple Values Example

<!DOCTYPE html>
<html>
<head>
<style>
   .container {
      width: 250px;
      background-color: lightblue;
      margin: 10px;
      padding: 10px;
      overflow: auto;
   }
</style>
</head>
<body>
<button onclick="setPixels()">Set 100px</button>
<button onclick="setPercentage()">Set 50%</button>
<button onclick="removeLimit()">Remove Limit</button>

<div id="demo" class="container">
<p>Content here. Content here. Content here.</p>
<p>More content. More content. More content.</p>
<p>Even more content to test height limits.</p>
</div>

<script>
function setPixels() {
    document.getElementById("demo").style.maxHeight = "100px";
}

function setPercentage() {
    document.getElementById("demo").style.maxHeight = "50%";
}

function removeLimit() {
    document.getElementById("demo").style.maxHeight = "none";
}
</script>
</body>
</html>

Key Points

  • Use overflow: auto or overflow: hidden to handle content that exceeds the maximum height
  • The maxHeight property doesn't force an element to be that height ? it only sets the upper limit
  • Setting maxHeight to "none" removes any height restriction

Conclusion

The maxHeight property provides flexible height control for dynamic content. Combine it with overflow properties to create scrollable containers when content exceeds the limit.

Updated on: 2026-03-15T23:18:59+05:30

826 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements