0

I want to position the content of a flex container to be in the center on the cross axis. As far as I know the "align-items" will do that however for "align-items" to work we need to specify the height explicitly. Am I right?

Okay, I specified the height explicitly but on the "header" block-level element which houses the flex-container. The flex container doesn't seem to care about the block container, though. Why does that happen? Is the flex container removed from the normal flow?

:root {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

.header {
  background: orchid;
  height: 100px;
}

.flex-container-1 {
  display: flex;
  align-items: center; /* this doesn't seem to work */
                       /* unless I specify the height on the
                          flex container itself */
}
<header class="header">
    <div class="flex-container-1">
      Flex Container 1
    </div>
</header>
Zoltan King
  • 1,964
  • 4
  • 18
  • 38
  • height on the element where you specify the align-items – Temani Afif Feb 25 '19 at 12:06
  • 2
    Your flex container is only as high as its content demands, it currently has no reason to grow to the height of its parent. – 04FS Feb 25 '19 at 12:06
  • Yes, but I noticed I can use "height: inherit;" on the flex-container and it will inherit the height from the parent. – Zoltan King Feb 25 '19 at 12:12
  • no need inherit or anything .. you are simply applying the height to the wrong element. What you said is true but the height need to be applied to the flex conainer where you are applying the `align-items` – Temani Afif Feb 25 '19 at 12:14
  • And if I have two flex-containers, an outer and an inner container and set the height on the outer one, the inner container will use the height from the outer container, right? – Zoltan King Feb 25 '19 at 12:18
  • 1
    This is a different case. If you have an outer flexbox container you will have the stretch effect that will make the height of the inner one the same as the outer but in all the cases, the height need to belong to the flex container where you apply the alignment (either explicitely set or implicitely by other properties) – Temani Afif Feb 25 '19 at 12:19

1 Answers1

3

You should give height:100%; to .flex-container-1

:root {
  box-sizing: border-box;
}

*, *::before, *::after {
  box-sizing: inherit;
}

.header {
  background: orchid;
  height: 100px;
}

.flex-container-1 {
  display: flex;
  align-items: center;
  height:100%;
}
<header class="header">
    <div class="flex-container-1">
      Flex Container 1
    </div>
</header>
doğukan
  • 23,073
  • 13
  • 57
  • 69