skip to Main Content

I put min-height: 100vh; on the body, then height: 100% on the main. For some reason, the main height does not stretch full to the parent.

https://codepen.io/pen/

Can somebody explain? Thanks.

I also tried adding other, but anything does not seem to work under the

body {
  border: 2px solid red;
  min-height: 100vh;
}

main {
   border: 2px solid green;
   height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body> 
  <main>hihihihasidfiojdi</main>
</body>
</html>

3

Answers


  1. The issue arises because setting height: 100%; on an element only works if the parent element also has a defined height. In your case, the main has height: 100%;, but its parent, body, has a min-height set to 100vh, not a fixed height. This means that the height of body is not explicitly defined, and thus main cannot inherit 100% of it.

    You can use flexbox on the body to ensure that main stretches to fill the remaining space.

    html, body {
        margin: 0;
        padding: 0;
        height: 100%;
    }
    
    body {
        border: 2px solid red;
        min-height: 100vh;
        display: flex;
        flex-direction: column;
    }
    
    main {
        border: 2px solid green;
        flex-grow: 1;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
    </head>
    <body> 
      <main>hihihihasidfiojdi</main>
    </body>
    </html>
    Login or Signup to reply.
  2. Change min-height: 100vh; to height: 100vh; in the body selector. If you specify a height in percent, there has to be an explicit height in the parent element (min-height will not set the height explicitly).

    Login or Signup to reply.
  3. Add main height as 100vh

    main {
       border: 2px solid green;
       height: 100vh;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search