1

I am having trouble understanding the default behavior of display: flex

Why does my header vertically centers its children when I only add display: flex to it.

I have not added align-items: center; to the header.

Is it because I assigned it height: 100px;?

header {
  display: flex;
  border: 1px solid black;
  height: 100px;
}

header div {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 1224px;
  margin: 0 auto;
}

nav a:not(:last-child) {
  margin-right: 55px;
}
<header>
  <div>
    <a href="#">Link</a>
    <nav>
      <a href="#">one</a>
      <a href="#">two</a>
      <a href="#">three</a>
     </nav>
     <a href="#">Link</a>
  </div>
</header>

I am aware that the div has display: flex and align-items: center; But why does the parent html element header also need display: flex for its children to vertically center?

dev_el
  • 2,357
  • 5
  • 24
  • 55

3 Answers3

2

When you apply display: flex to the parent div, its children "stretch" to assume the full height and width of the container, since the default align-items property is stretch.

Hence, the child of the header now has a height of 100px (previously the height of its content), and the content is centered.

Your solution (to apply height: 100%) works since the content's height is now 100px (the height of the container), essentially simulating flexbox's vertical stretch.

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    Removing `display: flex` from the `header` and giving my `div` a `height` of `100%` gave me the solution I wanted – dev_el Jul 30 '21 at 03:09
0

It is not aligning vertically the header, it is aligning vertically the div inside the header.

Your header > div has display:flex and align-items: center which is explicit telling the div to align items to the center.

caiovisk
  • 3,667
  • 1
  • 12
  • 18
0

You don't need display: flex; on parents with only one child. Your <header> tag has 100px of height and by default your <div> has implicit align-self: stretch; which is like you do height: 100% on it. For solving your problem you have two options:

  • Remove display: flex; from your <header> tag.
  • Asign align-self: flex-start; to your <div>.

Apply these two options to the <div> children for achieve the same results if you consider. The main key of this answer is: All children of a flex container has an implicit align-self: stretch by default.

  • I did what you suggested, but the children are not centered, unless I misinterpreted your instructions. https://codesandbox.io/s/header-center-chlyl?file=/src/styles.css – dev_el Jul 30 '21 at 03:02
  • In the case you need the children vertically centered, also add `height: 100%` to `
    ` keping `display: flex` removed from `
    ` tag. For this solution please, dont asign `align-self: flex-start;` to the `
    `. It is not necessary anymore.
    – Pablo David Gago Ballester Jul 30 '21 at 03:09