Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center inside a `flex-grow: 1`

Tags:

css

flexbox

say I have HTML as

<div class="page">
  <div class="header"></div>
  <div class="content">
    <div class="foo">
      <div>I want to be center of content</div>
    </div>
  </div>
  <div class="footer"></div>
</div>

css

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

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header {
  flex-shrink: 0;
  background-color: green;
  height: 50px;
}
.content {
  flex-grow: 1;
}
.footer {
  flex-shrink: 0;
  background-color: steelblue;
  height: 150px;
}

.foo {
  display: flex;
  justify-content: center;
  align-items: center;
}

https://codepen.io/rrag/pen/PRmOYe

I achieved a sticky footer at the bottom of the page using flex-grow but that leads to a content with unknown height

How do I center something in the middle of content? Is it possible using flexbox or may be an alternative approach?

like image 409
rrag Avatar asked Oct 16 '22 21:10

rrag


1 Answers

You have almost the exact right idea! Instead of setting your vertical centering rules on .foo (display: flex;, justify-content: center; and align-items: center;), you instead simply need to set them on the parent .content.

This can be seen in the following (Click Run snippet and thenFull page to see this in effect):

html,
body {
  height: 100%;
}

body {
  margin: 0;
}

.page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  flex-shrink: 0;
  background-color: green;
  height: 50px;
}

.content {
  flex-grow: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.footer {
  flex-shrink: 0;
  background-color: steelblue;
  height: 150px;
}
<div class="page">
  <div class="header"></div>
  <div class="content">
    <div class="foo">
      <div>I want to be center of content</div>
    </div>
  </div>
  <div class="footer"></div>
</div>

This can also be seen on CodePen.

like image 51
Obsidian Age Avatar answered Oct 21 '22 06:10

Obsidian Age