How to specify max-height css property to Screen size

Learn how to specify max-height css property to screen size with practical examples, diagrams, and best practices. Covers javascript, html, css development techniques with visual explanations.

Dynamically Sizing Elements: Setting max-height to Screen Size with CSS & JavaScript

Hero image for How to specify max-height css property to Screen size

Learn how to effectively control element heights using CSS max-height relative to the viewport, and explore JavaScript solutions for more dynamic and responsive sizing.

In web development, controlling the dimensions of elements is crucial for creating responsive and visually appealing layouts. While CSS offers various units for sizing, aligning an element's max-height directly with the screen's available height can be a common requirement. This article explores how to achieve this using pure CSS viewport units and, when necessary, more dynamic JavaScript approaches.

Understanding Viewport Units for max-height

CSS provides viewport-relative units that make it straightforward to size elements based on the browser's viewport dimensions. The vh (viewport height) unit is particularly useful for setting max-height relative to the screen. One vh is equal to 1% of the viewport's height. Therefore, to make an element's max-height equal to the full screen height, you would use 100vh.

.full-height-element {
  max-height: 100vh; /* Sets max-height to 100% of the viewport height */
  overflow-y: auto; /* Add scroll if content exceeds max-height */
  border: 1px solid #ccc;
}

Using 100vh to set an element's max-height to the full viewport height.

Handling Dynamic Content and Layouts with JavaScript

While 100vh is excellent for static scenarios, sometimes you need more granular control or need to account for other elements on the page (like a fixed header or footer) when calculating the available height. In such cases, JavaScript can provide the flexibility to dynamically calculate and apply max-height values. This is particularly useful when the available space changes due to user interaction, content loading, or responsive design adjustments.

flowchart TD
    A[Page Load/Resize Event] --> B{Calculate Available Height}
    B --> C{Identify Fixed Elements (Header, Footer)}
    C --> D{Subtract Fixed Heights from Viewport Height}
    D --> E[Set Element's max-height CSS Property]
    E --> F[Render/Update Layout]

Workflow for dynamically setting max-height using JavaScript.

document.addEventListener('DOMContentLoaded', setMaxHeight);
window.addEventListener('resize', setMaxHeight);

function setMaxHeight() {
  const headerHeight = document.querySelector('header')?.offsetHeight || 0;
  const footerHeight = document.querySelector('footer')?.offsetHeight || 0;
  const availableHeight = window.innerHeight - headerHeight - footerHeight;

  const targetElement = document.getElementById('my-scrollable-content');
  if (targetElement) {
    targetElement.style.maxHeight = `${availableHeight}px`;
  }
}

// Initial call if DOMContentLoaded already fired
if (document.readyState === 'complete') {
  setMaxHeight();
}

JavaScript function to calculate and set max-height dynamically, accounting for header and footer.

Combining CSS and JavaScript for Robust Solutions

For the most robust solutions, a combination of CSS and JavaScript often yields the best results. You can use CSS for the initial styling and common cases, then layer JavaScript for specific dynamic adjustments or to address edge cases that pure CSS might struggle with. For instance, you might use max-height: 100vh as a fallback or default, and then override it with JavaScript if a more precise calculation is needed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Max-Height Example</title>
    <style>
        body {
            margin: 0;
            font-family: sans-serif;
        }
        header {
            background-color: #333;
            color: white;
            padding: 15px;
            text-align: center;
            height: 60px; /* Fixed header height */
        }
        footer {
            background-color: #eee;
            padding: 10px;
            text-align: center;
            height: 40px; /* Fixed footer height */
        }
        #my-scrollable-content {
            background-color: #f9f9f9;
            padding: 20px;
            overflow-y: auto; /* Enable scrolling if content overflows */
            /* Initial max-height can be set here, or left to JS */
            max-height: calc(100vh - 100px); /* CSS fallback/initial value */
        }
        .content-filler {
            height: 150vh; /* Make content taller than screen to demonstrate scrolling */
            background-color: lightblue;
            padding: 20px;
            box-sizing: border-box;
        }
    </style>
</head>
<body>
    <header><h1>My Application Header</h1></header>
    <main id="my-scrollable-content">
        <h2>Scrollable Content Area</h2>
        <p>This area's max-height is dynamically adjusted to fit the screen, accounting for the header and footer.</p>
        <div class="content-filler">A lot of content to demonstrate scrolling within the constrained max-height.</div>
    </main>
    <footer><p>&copy; 2023 Dynamic Height Example</p></footer>

    <script>
        document.addEventListener('DOMContentLoaded', setMaxHeight);
        window.addEventListener('resize', setMaxHeight);

        function setMaxHeight() {
            const headerHeight = document.querySelector('header')?.offsetHeight || 0;
            const footerHeight = document.querySelector('footer')?.offsetHeight || 0;
            const availableHeight = window.innerHeight - headerHeight - footerHeight;

            const targetElement = document.getElementById('my-scrollable-content');
            if (targetElement) {
                targetElement.style.maxHeight = `${availableHeight}px`;
            }
        }

        if (document.readyState === 'complete') {
            setMaxHeight();
        }
    </script>
</body>
</html>

Complete HTML, CSS, and JavaScript example demonstrating dynamic max-height.