Coding Challenge - #5: 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.

1 Like

Welcome to the forums @adnanahmed :grinning_face:

Hey @adnanahmed, welcome. Good to have you here.

Challenge solution: The challenge is to center a div both horizontally and vertically using flexbox without fixed pixel offsets or absolute positioning.

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 container ‘.stage’, we enable flexbox layout. ‘justify-content: center’ centers the flex items along the main axis (horizontally in a row-direction flex container). ‘align-items: center’ centers the flex items along the cross axis (vertically in a row-direction flex container), achieving perfect centering.


Got it: @adnanahmed :trophy:

First-answer leaderboard

  1. @kirupa - 4 (firsts) :trophy:
  2. @adnanahmed - 2 (firsts)
  3. @emmawalter5 - 1 (first)

Oh nice