Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: autooroverflow: hiddento handle content that exceeds the maximum height - The
maxHeightproperty doesn't force an element to be that height ? it only sets the upper limit - Setting
maxHeightto"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.
Advertisements
