CSS Align

Centre elements horizontally and vertically.

✍️ 3 exercises + code challenge in this lesson

Centring is one of the most common tasks in CSS. The right technique depends on what you are centring:

  • Text: text-align: center.
  • A block with a width: margin: 0 auto.
  • Anything, both directions: on the parent, display: flex; justify-content: center; align-items: center;
  • With Grid: display: grid; place-items: center;

Key Takeaways: CSS Align

Mastering CSS Align helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Align Code Example

CSS
<style>
  .box  { height: 120px; background: #F1F5F9; border: 2px dashed #CBD5E1; margin-bottom: 12px; }
  .flex { display: flex; justify-content: center; align-items: center; }
  .grid { display: grid; place-items: center; }
  .item { background: #2563EB; color: white; padding: 10px 16px; border-radius: 8px; }
  .auto { width: 200px; margin: 0 auto; text-align: center; background: #14B8A6; color: white; padding: 8px; }
</style>

<div class="box flex"><div class="item">Flexbox centred</div></div>
<div class="box grid"><div class="item">Grid centred</div></div>
<div class="auto">margin: 0 auto</div>
Free sign-in required · Google login available

CSS Align Practice Exercises

Check what you learned in “CSS Align”.

/ 3 solved
Fill in the blank

Centre the children both ways with Flexbox.

.parent {
  display: flex;
  justify-content: ;
  align-items: ;
}
✓ Correct! Not quite. Try again.
Multiple choice

Which Grid shorthand centres items in both directions?

✓ Correct! Not quite. Try again.
Code challenge

Centre the .item horizontally and vertically inside .parent using Flexbox.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services