Mastering CSS Align-items and Align-self for Seamless Layouts

align-items and align-self are CSS properties used in the context of flexbox and grid layouts to control the alignment of items within a container. These properties are part of the alignment properties in CSS and are particularly useful when working with flex containers.

align-items:

  1. The align-items property is used to align items along the cross axis of the container. In a flex container, the cross axis is perpendicular to the main axis.

  2. It accepts the following values:

i. stretch (default): Items are stretched to fill the container. ii. flex-start: Items are aligned at the start of the cross axis. iii. flex-end: Items are aligned at the end of the cross axis. iv. center: Items are centered along the cross axis. v. baseline: Items are aligned such that their baselines align.

.container {
  display: flex;
  align-items: center;
}

In this example, items inside the flex container will be centered along the cross axis.

align-self:

  1. The align-self property is used to override the align-items property for individual flex items. It allows you to specify the alignment for a specific item.

  2. It accepts the same values as align-items.

.item {
  align-self: flex-end;
}

In this example, the specific item with the class “item” will be aligned to the end of the cross axis, regardless of the align-items property set on the container.

Here’s a simple HTML example to illustrate both properties:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .container {
      display: flex;
      height: 200px;
      align-items: center; /* Align items vertically in the center */
    }

    .item {
      width: 50px;
      height: 50px;
      background-color: lightblue;
      margin: 5px;
    }

    .item:nth-child(2) {
      align-self: flex-end; /* Override alignment for the second item */
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
  </div>
</body>
</html>

Output

Screenshot-2023-11-12-183503 In this example, the items are placed in a flex container, and the `align-items: center;` style centers them along the cross axis. The second item, however, has its alignment overridden by `align-self: flex-end;`, so it aligns to the end of the cross axis.
Previous
Optimizing Layouts with CSS Justify-content Flex-start to Space-evenly
Next
What is Grid in CSS and How to use Grid CSS better way