Ensuring complete height and width with no scrollbar in a Material UI React application

I'm attempting to create a page that fills the entire height of the screen without adding an undesirable scrollbar. When I say 100% height, I mean it should just fit the size of the screen.

Here is a demonstration of the issue. The yellow highlighted area represents the unwanted added height, and there is also a horizontal scrollbar present:

https://i.stack.imgur.com/yz07O.png

Below is the code snippet for rendering the page:

return (
    <>
        <Box display='flex' flex='1' justifyContent='space-around'>
            <IndexSelector
                id='index'
                value={symbol}
                onChange={this.onSymbolChange}/>
            <SeriesSelector
                id='series'
                seriesList={Form.seriesList}
                onChange={this.onSeriesChange}/>
            <DateRange fromDate={fromDate} toDate={toDate} onChange={this.onDateChange}/>
        </Box>

        <Box height='100%' border='1px solid red' marginTop='50px'>
            <Graph instructions={this.getInstructions()} apiData={this.apiData} />
        </Box>
    </>
)

The following CSS is used in index.css:

html {
  box-sizing: border-box;
}

html, body, #root {
  padding: 0px !important;;
  margin: 0px !important;;
  height: 100vh;
  width: 100vw;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
  monospace;
}

Any suggestions on how to eliminate the extra height and width, and ensure the red-bordered container fills the full height?

EDIT: I followed @gowatham's suggestion but didn't achieve the desired outcome. Here's what I got:

EDIT 2:

HTML: https://pastebin.com/Qu2RFHe7 CSS: https://pastebin.com/1z3Zg5rv

https://i.stack.imgur.com/UvBz8.png

Answer №1

To achieve a responsive layout where the main container takes up 100% of the viewport height and displays its children in a column direction using flexbox, you can set the result container to take up the remaining space by applying flex: 1. Additionally, you can make the content inside this container scrollable by setting overflow: auto.

An advantage of this method is that it allows the filter container to have variable heights and still function correctly.

<Box height="100vh" display="flex" flexDirection="column">
  <Box>Filter</Box>
  <Box flex={1} overflow="auto">
    {Array.from(Array(100)).map((v, i) => (
      <div key={i}>Testing {i}</div>
    ))}
  </Box>
</Box>

https://codesandbox.io/s/material-demo-ntvoj

Another solution, which may work in older browsers, involves setting the filter container to position: fixed and ensuring that the element following it has enough margin-top or padding-top to prevent its content from overlapping when scrolled to the top.

<Box
  position="fixed"
  top={0}
  height="60px"
  width="100%"
>
  Filter
</Box>
<Box marginTop="60px">
  {Array.from(Array(100)).map((v, i) => (
    <div key={i}>Testing {i}</div>
  ))}
</Box>

https://codesandbox.io/s/material-demo-4m85i

Answer №2

Mastering CSS styling may seem daunting at first, but once you have a solid plan for your page layout, it becomes much more straightforward.

An effective approach is to allocate 90% of the height to the body and reserve the remaining 10% for the filter box above. This ensures that the total height remains constant at 100%, unless modifications to the layout are desired. Here's an example:

return (
  <div style={{ height: '90vh', margin: 0, padding: 0 }}>
    <Box display='flex' flex='1' justifyContent='space-around' style={{ height: '10vh' }}>
        <IndexSelector
            id='index'
            value={symbol}
            onChange={this.onSymbolChange}/>
        <SeriesSelector
            id='series'
            seriesList={Form.seriesList}
            onChange={this.onSeriesChange}/>
        <DateRange fromDate={fromDate} toDate={toDate} onChange={this.onDateChange}/>
    </Box>

    <Box style={{ maxHeight: "100%", overflow: "auto" }}>
        <Graph instructions={this.getInstructions()} apiData={this.apiData} />
    </Box>
  </div>
)

If a 1px border causes the height to exceed 100% resulting in a scrollbar, simply add overflow: hidden to the parent div to hide the scrollbar. Explore this concept further on CodeSandbox:

https://codesandbox.io/s/material-demo-djgiu?fontsize=14

Answer №3

To find the difference in height between box1 and box2, follow these steps:

Set a reference to box1:
ref={(ref) => this.box1 = ref}

In box2, adjust the height using the calculated value:

height={`calc(100% - ${this.box1.clientHeight}px)`}

Here's an example implementation:

return (
    <>
        <Box display='flex' flex='1' justifyContent='space-around' ref={(ref) => this.box1 = ref}>
            <IndexSelector
                id='index'
                value={symbol}
                onChange={this.onSymbolChange}/>
            <SeriesSelector
                id='series'
                seriesList={Form.seriesList}
                onChange={this.onSeriesChange}/>
            <DateRange fromDate={fromDate} toDate={toDate} onChange={this.onDateChange}/>
        </Box>

        <Box height={`calc(100% - ${this.box1.clientHeight}px)`} border='1px solid red' marginTop='50px'>
            <Graph instructions={this.getInstructions()} apiData={this.apiData} />
        </Box>
    </>
)

Answer №4

Make sure to implement Flex for the Parent element as well

<div display='flex' flex='1' height='100%' justifyContent='space-between'> //consider using flex direction column in accordance with your library     
        <Box display='flex' flex='1' justifyContent='space-around'>
            <IndexSelector
                id='index'
                value={symbol}
                onChange={this.onSymbolChange}/>
            <SeriesSelector
                id='series'
                seriesList={Form.seriesList}
                onChange={this.onSeriesChange}/>
            <DateRange fromDate={fromDate} toDate={toDate} onChange= 
   {this.onDateChange}/>
        </Box>
        <Box>
            <Graph instructions={this.getInstructions()} apiData={this.apiData} />
        </Box>
    </div>

Answer №5

Instead of using height: 100% in the parent element, opt for height: '100vh' in CSS. When using 100%, it will only take up to the maximum height of all content and won't enlarge further. On the other hand, 100vh represents the vertical height of the entire window. Don't forget to check the overflow-y property as well.

Answer №6

I adjusted the heights of the navigation division to 15vh, the following division to 20vh, and the last division to 65vh, totaling 100 vh, which is the height of the device. Feel free to customize these heights as needed. In the desktop view, there is no scrollbar present.

Check out the responsive design on my CodePen page. (I used the code provided in pastebin link shared) https://i.stack.imgur.com/Rky4d.png

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

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

The horizontal scrolling with overflow-x is not functioning correctly as it is displaying the scrollbar for the vertical

I am perplexed as to why I am unable to scroll horizontally to view the other pink thumbs. Despite adding an overflow of scroll-x to the thumbs container, which should theoretically allow horizontal scrolling, it only seems to scroll vertically. Could som ...

What is the best way to transfer data from the backend (express) to the frontend (react) within a single application?

I am working on a project that consists of an express app with React JS for the view. I have implemented client-side routing using react-router, and now there is a requirement to fetch remote configuration data. This data will be used to determine whether ...

Using relative positioning in CSS causes the div to move to a new line

Feel free to check out this demo I've created for reference: http://jsfiddle.net/jcb9xm44/ In a nutshell, the scenario involves two inline-block divs nested within a parent div: <div class="outer"> <div class="inner1"> Y & ...

Solutions for altering the appearance of a combobox using CSS

Currently, I am experimenting with javafx 2 and trying to modify the background color of the menu/list through CSS. Despite attempting the code snippet below, nothing seems to be working as expected. Do you have any suggestions or insights on how to achi ...

What is the best way to eliminate the lower margin in the UI-Boostrap Angular Tab directive?

The ui.bootstrap.tabs directive, which can be found here, seems to have a default margin before displaying its content. https://i.stack.imgur.com/NECGA.png Here is the HTML snippet: <uib-tabset active="activeJustified" justified="false" id="tabSet" s ...

Go to a different route while transferring information

My website has a specific route (/account) that is only accessible to logged-in users. If a user is not authenticated, the following code snippet handles the situation: // Redirect to login if no custom access token found if (!customerAccessToken) return r ...

Utilizing JQuery to track DIV clicks

I am encountering an issue with DIV clicks while using JQuery. I need guidance on this problem. Within my HTML, there are three designated DIV elements: <html> <body> <div id="overviewContainer"> <div id="firstContainer"></ ...

Tips for transferring properties from one React component to another React component

I need to figure out how to activate a button in a modal when text is entered into an input field. The form is part of a different class and is utilized within a parent class. How can I pass an onChange method to my form component? Check out the code for ...

Why is this text appearing twice on my screen?

When I run the code in my React app and check the console in Chrome, I notice that the response.data[0] is being printed twice. What could be causing this duplication? const fetchData = async () => { return await axios.get(URL) .then((respon ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

Learn how to dynamically incorporate multiple Bootstrap collapse elements in PHP

I've encountered an issue with my code that contains both HTML and PHP. The problem arises when there are multiple elements in a collapse, as only the first element works properly. This is due to the fact that each element has the same id named "colla ...

Container Based Absolute Positioning in Bootstrap

I am struggling with aligning text properly within a container. I want it to look like the image, but the text keeps ending up at the far right side of the page. Could you assist me in achieving this? Thank you! HTML: <header> <div class="c ...

Is there a way for me to change the color of a Checkbox in Material UI?

Currently, I am incorporating Material UI into my project and have encountered an issue with the Checkbox element. Placed within a div with a black background, the Checkbox itself appears in black as well. I would like to change the color of the Checkbox ...

In my Next.js project, I am looking for a way to make a modal continue to stay

I am looking to implement a feature where the modal remains visible even after a website refresh. Currently, when a user logs out, the page refreshes and the modal displaying "sign-out successful" disappears. My goal is to have the modal reappear after t ...

What is the best way to manage a redirect after signing in with Supabase?

I need help with redirecting to the dashboard page in Supabase. Currently, my code is set up to display the dashboard component based on user session, but I'd like to redirect to an account page after authentication instead. Any advice on how to achie ...

Update the iframe located on a different webpage

I am looking to create a dynamic button feature on my website where clicking a button on page1.html will open a new page (portal.html) with an iframe displaying the URL specified in the button. The setup involves two main pages: page1.html, and portal.htm ...

Redux: Double rendering issue in mapStateToProps

I've recently delved into learning Redux, and I've encountered an issue that's been on my mind. import React, { useEffect } from "react"; import { connect, useDispatch } from "react-redux"; import Modal from "../Moda ...

Dynamic Height in React Material-UI Table with Sticky Headers and Multiple Rows

Currently, I am working with React and Material-UI to create a table that needs to have a sticky header for a multi-row table head. The challenge I'm facing is that I don't want to specify a fixed height for the table, but instead have all lines ...

Having trouble establishing a connection with mongoose and typescript

When attempting to establish a connection using mongoose, I consistently encounter the errors outlined below. However, if I use MongoClient instead, everything functions as expected. import connectMongo from '../../lib/connectMongo' console.log( ...