London Smith London Smith - 10 days ago 7
CSS Question

Flex aligner working on Firefox/Edge, not on Chrome

I can't make a aligner working with Chrome, yet it's working on both Firefox and Edge.

I am using flex CSS:

body {
min-height: 100%;
display: flex;
flex-direction: column;
}

wrapper {
height: 100%;
/* flex: 1; would be enough but it looks bad in IE */
flex: 1 0 auto;
background-color: #3D9970;
}

.aligner {
height:100%;
display: flex;
align-items: center;
justify-content: center;
}

.aligner-center {
max-width: 50%;
background-color: #ffb443;
padding: 20px;
}


You see result here

I also tried with
display:table
with no success.

Any idea how to align center my Login Form div with Chrome too?

Thanks

Answer

That is expected behavior in Chrome as it has a stricter implementation of the Flexbox spec (take a look at this thread too):

  1. The default stretch value of align-self property changes only the used value of the element's cross size property (height in this case).

  2. Percentages are calculated from the explicitly specified value of the parent's cross-size property, not it's used value.

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto' (Source: W3C).

That means that setting height:100% on aligner which is the child of wrapper (in turn the flex child of a flexbox). Since we haven't specified a height on wrapper, that means it will pick 100% of the default height, which is auto.

Solution:

One of the solutions is to make your wrapper a flexbox too and give width: 100% for the aligner - see demo below:

html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}
wrapper {
  height: 100%;
  /* flex: 1; would be enough but it looks bad in IE */
  flex: 1 0 auto;
  background-color: #3D9970;
  display: flex;
  align-items: center;
  justify-content: center;
}
.aligner {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.aligner-center {
  max-width: 50%;
  background-color: #ffb443;
  padding: 20px;
}
body {
  font: 16px/1.5 sans-serif;
}
p {
  margin-bottom: 1em;
}
header,
wrapper,
footer {
  padding: 2em;
  color: white;
}
header {
  background-color: #85144B;
}
footer {
  background-color: #001F3F;
}
<header>
  Header
</header>
<wrapper>
  <div class="aligner">
    <div class="aligner-center">
      Login Form
    </div>
  </div>
</wrapper>
<footer>
  Footer
</footer>