CSS

Aligning Content Vertically Within Flex Items

Learn how to use Flexbox properties like `align-items` on the container and `align-self` on individual items to precisely control the vertical alignment of elements.

.flex-container {
  display: flex;
  align-items: flex-start; /* Default for all items */
  border: 1px solid #ccc;
  min-height: 200px;
  padding: 10px;
  gap: 10px;
}
.flex-item {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column; /* Allows internal content to stack vertically */
  justify-content: space-between; /* Pushes first child to top, last child to bottom */
}
.flex-item.align-center {
  align-self: center; /* Overrides container's align-items for this item */
}
.flex-item.align-end {
  align-self: flex-end; /* Overrides container's align-items for this item */
}
.flex-item p {
  flex-grow: 1; /* Allows paragraph to grow and push other content */
}
.flex-item .button {
  background-color: #007bff;
  color: white;
  padding: 8px 12px;
  border: none;
  cursor: pointer;
  margin-top: auto; /* Pushes this button to the bottom if preceding content varies */
}
How it works: This snippet demonstrates how to control vertical alignment for flex items. The `.flex-container` sets `align-items: flex-start;` by default, aligning items to the top of the cross-axis. Individual items can override this with `align-self`, as shown with `.align-center` and `.align-end`. By making a flex item itself a flex container (`display: flex; flex-direction: column;`), you can use `margin-top: auto;` on an inner element (like a button) to push it to the bottom, useful for consistently aligning elements in cards with varying content heights.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs