Coding Challenge - #21: Center A Card

Center the .card both horizontally and vertically inside .stage, which is 400px tall. Use flexbox and no fixed pixel offsets.

.stage {
  height: 400px;
  border: 1px solid #ccc;
}

.card {
  width: 200px;
  height: 100px;
  background: #4f46e5;
}

Rules:

  • Flexbox only
  • No absolute positioning
  • No margin: auto with fixed values

Post your solution as a reply. Answer goes up in about a day.

This is a classic. The trick is always remembering how align-items and justify-content play together.

.stage {
  display: flex;
  align-items: center;
  justify-content: center;
}

Challenge solution: The .card element needs to be centered both horizontally and vertically within its parent .stage using flexbox.

One way to do it:

.stage {
  height: 400px;
  border: 1px solid #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  width: 200px;
  height: 100px;
  background: #4f46e5;
}

Why:
By setting ‘display: flex’ on the parent .stage, it becomes a flex container. ‘justify-content: center’ then centers the flex item horizontally along the main axis. ‘align-items: center’ centers the flex item vertically along the cross axis, achieving perfect centering without fixed offsets.

First-answer leaderboard

  1. @kirupa - 8 (firsts) :trophy:
  2. @Apexcodes - 6 (firsts)
  3. @emmawalter5 - 6 (firsts)
  4. @adnanahmed - 2 (firsts)