CSS Align

Subject: css

CSS Align

CSS Alignment is the process of placing elements properly within their parent container. This includes text alignment, horizontal and vertical alignment, and aligning elements using modern layout techniques like Flexbox and Grid.


1. Text Alignment Using text-align

The text-align property is used to align text content within block-level elements.

Syntax:

Example:


2. Horizontal Alignment of Block Elements Using Margin

To center block-level elements like <div>, use margin: auto with a fixed width.

Example:


3. Aligning Elements with Flexbox

Flexbox provides powerful utilities for both horizontal and vertical alignment.

Example:


4. Vertical Alignment Using line-height (for text)

You can align text vertically inside an element by setting the line-height equal to the element's height.

Example:


5. CSS Grid Alignment (Modern Approach)

Grid layout allows precise control over alignment using justify-items and align-items.

Example:


Key Takeaways

  • Use text-align for aligning text (left, center, right, justify)
  • Use margin: auto to center block-level elements horizontally
  • Flexbox is ideal for aligning elements both horizontally and vertically
  • Use line-height to center text vertically inside elements
  • CSS Grid supports easy alignment with place-items, justify-items, and align-items