1

I am trying to create a flexbox that vertically aligns two headings inside their container. I can get the vertical alignment to work using align-items however both headings end up on the same line.

To resolve this I added a flex-direction property which splits the headings onto separate lines but then also horizontally centers the text and removes the vertical centering.

I thought maybe adding justify-content might help but it has no effect.

Here's an example: https://jsfiddle.net/efarley/Lfw3n6ba/3/

.container {
  align-items: center;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  height: 40px;
  width: 400px;
}

.container2 {
  align-items: center;
  border: 1px solid black;
  display: flex;
  height: 40px;
  width: 400px;
}

h1, h2 {
  font-size: 12px;
  margin: 0px;
}
<div class='container'>
  <h1>
    heading 1
  </h1>
  <h2>
    heading 2
  </h2>
</div>
<br />
<div class='container2'>
  <h1>
    heading 1
  </h1>
  <h2>
    heading 2
  </h2>
</div>

As you can see the first container has both align-items and flex-direction properties, while the second container does not have the flex-direction.

efarley
  • 8,371
  • 12
  • 42
  • 65

1 Answers1

1

flex-direction: column

.container {
  display: flex;
  flex-direction: column;
  align-items: center;              /* horizontal alignment */
  justify-content: center;          /* vertical alignment */
  height: 40px;
  width: 400px;
  border: 1px solid black;
}

h1,
h2 {
  font-size: 12px;
  margin: 0px;
}
<div class='container'>
  <h1>heading 1</h1>
  <h2>heading 2</h2>
</div>

flex-direction: row

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: center;     /* vertical alignment (for multiple lines ) */
  justify-content: center;   /* horizontal alignment */
  height: 40px;
  width: 400px;
  border: 1px solid black;
}

h1, h2 {
  flex: 0 0 100%;             /* force one item per row */
  text-align: center;         /* center text in each element */
  font-size: 12px;
  margin: 0px;
}
<div class='container'>
  <h1>heading 1</h1>
  <h2>heading 2</h2>
</div>

Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701