0

I am attempting the following solution described at https://stackoverflow.com/a/22218694/1175080.

Alternatively, instead of aligning the content via the container, flexbox can also center the a flex item with an auto margin when there is only one flex-item in the flex container (like the example given in the question above).

Here is my solution.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
  main {
      display: flex;
      height: 100%;
      background: lightgreen;
  }

  section {
      margin: auto;
      background: yellow;
  }
</style>
</head>
<body>
  <main>
      <section>Foo</section>
  </main>
</body>
</html>

It does not seem to work. The main element does not expand to occupy 100% height of the page. What am I doing wrong? How can this be made to work?

Ason
  • 79,264
  • 11
  • 79
  • 127
Lone Learner
  • 12,094
  • 14
  • 66
  • 159

3 Answers3

0

Assign html, body with 100% width & height, Like:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
}

Have a look at the snippet below:

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
}
main {
    display: flex;
    height: 100%;
    background: lightgreen;
}

section {
    margin: auto;
    background: yellow;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<main>
    <section>Foo</section>
</main>
</body>
</html>

Hope this helps!

Saurav Rastogi
  • 8,959
  • 3
  • 25
  • 34
0

Used height:100vh

body {
  min-height: 100vh;
  margin: 0;
}
main {
  display: flex;
  height: 100vh;
  background: lightgreen;
}

section {
  margin: auto;
  background: yellow;
}
<main>
    <section>Foo</section>
</main>
Minal Chauhan
  • 5,739
  • 5
  • 15
  • 36
0

The main element will use the space allotted to by it's parents, which in this case are body > html. Therefore, set both body and html to have a height of 100% as well and you should be golden.

 html, body {
    height: 100%;
 }
Parks
  • 480
  • 5
  • 8