0

I have very specific request for centering elements so I decided to try flexbox.

The request is following. I have 3 elements stacked vertically.

Header, content and footer.

A special condition is there to have middle element "content" centered on page (vertically and horizontaly) and header with footer stick on it from top and down. It should works with window resize. There is hard-coded solution for better demonstration. http://codepen.io/anon/pen/oXjVmE

I tried to solve that with flex box, but only what I get is that all 3 elements are centered together.

I am looking how to tell flex-box "First and last element should be same and max possible height" http://codepen.io/anon/pen/GJpeYY

html

<div class="wrapper">
  <div class="header">
    <h1>Header</h1>
    <h2>Subheader</h2>
    <p>Text</p>
  </div>
  <div class="centered">
    Centered Text
  </div>
  <div class="footer">
    Some tiny footer
  </div>
</div>

css

.wrapper {
  height:500px;
  background-color:lightgreen;
  .display(flex);
  .flex-direction(column);
  .align-items(center);
  .justify-content(center);
  text-align: center;
}

.header {
   background-color:gold;
}

.centered {
  height: 50px;
  line-height: 50px;
  background-color:deepskyblue;
}

.footer {
  background-color:tomato;
}
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Schovi
  • 1,960
  • 5
  • 19
  • 33

2 Answers2

2

You can achieve that result by simply using flex: inline-flex, and adding an outer container, like in the following

running demo

I've made the centered text content editable, so edit it and see that header and footer stretches themselves along with it.

.container {
  text-align: center;
  background-color: lightgreen;
}
.wrapper {
  height: 500px;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
}
.header {
  background-color: gold;
}
.centered {
  height: 50px;
  line-height: 50px;
  background-color: deepskyblue;
}
.footer {
  background-color: tomato;
}
<div class="container">
  <div class="wrapper">
    <div class="header">
      <h1>Header</h1>
      <h2>Subheader</h2>
      <p>Text</p>
    </div>
    <div class="centered" contentEditable="true">
      Centered Text - I'm editable, so... EDIT ME !!!!
    </div>
    <div class="footer">
      Some tiny footer
    </div>
  </div>
</div>

Also FlexyBoxes tool is worthy a try for this kind of things.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
0

remove wraper height:500px; and add height:100vh;

it is viewport height and i hope you will get what you want.

Alex
  • 8,461
  • 6
  • 37
  • 49
Danish Khan
  • 143
  • 1
  • 9
  • Height of wrapper does not matter. I set 500px for limit wrapper to look like monitor (4:3). When wrapper is 100% or 100vh or 100px, elements are still centered together like one big element. When header is large as it is in example then content and footer are pushed down. – Schovi May 07 '15 at 13:02