What is the best way to establish a consistent height for every smartphone?

As a junior front-end developer, I am facing a challenge.

I have fixed header and footer areas on the page.

My goal is to set the height of the "box container" dynamically.

If the content in the box container exceeds the set height, I want it to scroll.

For example, if the total height of the device is 600px, with a 100px header and footer, I aim to set the box container's height to 400px.

The scrolling should begin once the box container surpasses the footer element.


    PAGE VIEW ON PHONE (600px)
     ----- 
     HEADER (100px)
     -----
     
     BOX CONTAINER WITH SCROLL (400px with overflow scroll)

     -----
     FOOTER (100px)
     -----

     another page
     -----
     HEADER (100px)
     -----

     ANOTHER ELEMENT (200px)
     
     SECOND BOX CONTAINER WITH SCROLL (200px overflow scroll)

     -----
     FOOTER (100px)
     -----

This code example illustrates the structure:


    <div className="App">
      <header>this is header</header>
      <div>.... another content....</div>
      <div className="boxContainer">
        <div className="box" />
        <div className="box" />
        ...
      </div>
      <footer>this is footer</footer>
    </div>

.boxContainer {
  /* How can I achieve dynamic height? */
  height: 300px; // Starting point for testing
  overflow: scroll;
}

.box {
  background-color: red;
  width: 100%;
  height: 100px;
  margin: 10px 0px;
}

.box:nth-child(2n) {
  background-color: blue;
}

What steps should I take next?

I considered calculating the total pixel values of the header and footer sections for each page, subtracting from the device height, then providing the box container a fixed height using inline-style. However, this approach seemed cumbersome as it required customization for every page due to possible additional elements beyond just the header and footer. I believe there might be a better solution out there.

Answer №1

It can be challenging to adjust the height of a boxContainer without JavaScript, but since you are utilizing React, you can perform the calculation after the component has mounted and then set the height accordingly:

  componentDidMount(){
    const elements = document.querySelectorAll('.App > *:not(.boxContainer)');
    var height = 0;
    for (const element of elements.values()) {
        let style = window.getComputedStyle(element);
      height += parseInt(style.height);
    }
    document.querySelector(':root').style.setProperty('--box-container-height', height+'px');
    /* 
    another method involves using a state variable
    this.setState({ 
      boxContainerHeight : `calc(100vh - ${height}px)`
    }) */
  }

Using setState is considered an antipattern (as it triggers the render() method again), so it's recommended to utilize CSS variables instead. For a complete demonstration, check out: https://jsfiddle.net/m9rqsL4j/13/

Answer №2

Implement the Viewport Height attribute for responsiveness.

header {
  height: 2.8vh;
}

.container {
  height: /* customize as needed */;
  /* height: 70vh; */
  overflow: auto;
}

footer {
  height: 2.8vh;
}

Experiment with Percentage values, but I personally recommend using viewport height for better results.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to use JavaScript to remove line breaks from an h1 tag

Is there a way to remove the line break that occurs after an H1 element? Also, I am searching for a method to add a backspace functionality using JavaScript. ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

The button adjacent to my input consistently appears beneath the input field

I am currently working on a blog that consists of entries. I have included a form with hidden variables to delete posts by submitting the entry ID and other data. However, I am facing an issue where the delete button always displays below the entry instead ...

Arrange buttons and input fields within Dash in a cohesive layout

I'm currently developing a Dash application and I need to align two input fields and two buttons in two separate rows. I want the button 'Download ClinicalTrial.gov info' to be placed alongside the input 'Insert the filename for RCT inf ...

ReactJS event handling is functioning properly with only a subset of the props, not all of them

I am currently facing an issue with sending the id prop to an event handler for handling an event. I have a map function that sends both the name and id as props, but when trying to send the id to the event handler in the Delete Todo component, it shows ...

Troubleshooting Problem with Bootstrap 4 Navigation Drop-Down Menu

I am working on developing some navigation forms for my university projects. I encountered an issue where I selected the Book item, and the navigation was working fine. However, when I selected Child items and then clicked on the Organization item, the nav ...

What causes the $_FILES superglobal to consistently appear empty?

Check out my page Take a look at my form: <h2>Upload Photo</h2> <form name="photo" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> Photo <input type="file" name="image" size="30" /> & ...

Difficulty transitioning from still image to video on mouseover in Next.js

I'm creating a website where hovering over an image should trigger a video to play. However, there are instances where there is a delay or the screen flashes blank before the video begins. I've worked on optimizing the video files by reducing th ...

Using Strapi to showcase images in a React frontend

I am currently in the process of developing a website utilizing Strapi as a Content Management System (CMS) and Next.js with React for the Frontend. The website features an image slider that includes an image, a headline, and a description. While I have su ...

Updating the Scale of the Cursor Circle on my Portfolio Site

I attempted to find tutorials on creating a unique circle cursor that can hide the regular mouse cursor as well. After implementing it with a difference blend mode, I encountered an issue where I wanted the scale to change when hovering over a link. The ...

Convert a Form to a query string using mootools

Trying to serialize an entire form has been a bit tricky for me. I thought I had found the simplest way: var tmp = $('myForm').toQueryString().parseQueryString(); var req = JSON.decode( tmp ); However, it seems like this method is not working a ...

Increase the worth of a particular element within an array based on its index position

Is there a way to update the value of a specific object in an array based on its index? I tried the following code, but it ends up adding a new object to the array. Instead, I want to update the "errors" property of an existing object at a specific index ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Adjusting the height of a DIV element to suit the window dimensions

I am facing an issue with the following HTML code: <div id="subpageHeaderImageSection"> <div id="subpageHeaderLeft"> <span id="holdImageP"></span> <!--[if lte IE 10]><img id="igm" src="theImages/sub ...

Having trouble with named anchor link not functioning in Internet Explorer. I have attempted the recommended fixes from Stack Overflow with no

My issue involves using a named anchor tag: <table id="search_results" name="search_results"> When I try to link to it like this: pagename.php#search_results It works in Firefox and Chrome, but not in IE (8). I have explored using an <a> t ...

Sluggish content loading in an Android application

Currently, I am working on creating a social sharing and community app using HTML5 specifically for Android phones. One issue that I have noticed is the slow loading speeds of content when scrolling up or down, as well as when posting new content. I am lo ...

What is the process for submitting a record to a table following the activation of a JavaScript link or button

I am working on creating a like-unlike button below each post for registered users to interact with. I have successfully created the button itself, but now I need to figure out how to store records when a user clicks the button. My idea is to utilize a tab ...

Embed API requests using JavaScript's Axios library to ensure the correct promise is returned

I am currently facing an issue with posting data to my API using axios. In order to make the request, I need to include a XSFR-token along with it. The technologies I am using for this are React, Redux, Thunk, and Axios. The problem lies in handling this ...

organizing div class tiles in a vertical layout

I am facing a challenge in arranging the class named tile along with some additional elements to create a vertical list. The tiles vary in size and are not displaying vertically as intended. I also want to add text next to each tile without disrupting the ...

What is the best way to format each <li> element onto a separate line?

Creating a review section for an item on my website required me to organize the reviews and comments. I utilized the following code structure: <ul> <li> Comment code </li> <li> Comment code </li> </ul> Within the ...