CSS Align


🔹 What is CSS Alignment?

In CSS, alignment refers to positioning elements horizontally or vertically in a container.
There are different alignment techniques depending on whether you're aligning:

  • Text

  • Block elements

  • Inline elements

  • Flexbox/Grid items


🔸 Types of Alignment in CSS

1. Text Alignment

Use the text-align property to align inline content like text, inline images, or inline-block elements inside a block container.

text-align: left | right | center | justify;
🔹 Example:
<p class="centered-text">This paragraph is centered.</p>
.centered-text {
  text-align: center;
}

2. Vertical Alignment (Inline Elements)

Use vertical-align to align inline or inline-block elements vertically relative to the line box.

vertical-align: baseline | top | middle | bottom | text-top | text-bottom;
🔹 Example:
<img src="icon.png" class="v-align"> Text next to icon
.v-align {
  vertical-align: middle;
}

3. Aligning Block Elements (Horizontally)

To center a block element (like <div>) horizontally:

Method 1: margin: auto (with fixed width)
.center-block {
  width: 300px;
  margin: 0 auto;
}
Method 2: Using Flexbox
.parent {
  display: flex;
  justify-content: center;
}

4. Flexbox Alignment

Flexbox provides powerful alignment options:

display: flex;
justify-content: center;   /* horizontal */
align-items: center;       /* vertical */
🔹 Example:
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

5. Aligning Items in Grid

CSS Grid uses these properties:

justify-items: start | center | end;
align-items: start | center | end;

Practice Questions

Q1. Align text to the right inside a <div>.

Q2. Center a heading inside its container.

Q3. Vertically align an icon next to text.

Q4. Horizontally center a block element with fixed width.

Q5. Center text both horizontally and vertically using Flexbox.

Q6. Create three buttons spaced evenly using Flexbox.

Q7. Align a grid item to the bottom inside a grid container.

Q8. Justify a paragraph to make both edges aligned.

Q9. Use text-align to center an image inside a block.

Q10. Vertically center two inline-block elements.


Go Back Top