Home >Web Front-end >CSS Tutorial >How to Center a Middle Item in a Flexbox Container with Uneven Side Boxes?

How to Center a Middle Item in a Flexbox Container with Uneven Side Boxes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-19 20:45:10303browse

How to Center a Middle Item in a Flexbox Container with Uneven Side Boxes?

Centered Middle Item with Asymmetrical Side Boxes

The goal is to center the middle item in a container when its adjacent items have different widths, preserving the proper alignment regardless of content overflow.

Using Flexbox

Flexbox provides a solution using nested containers and automatic margins:

.container {
  display: flex;
}

.box {
  flex: 1;
  display: flex;
  justify-content: center;
}

.box:first-child > div { margin-right: auto; }
.box:last-child  > div { margin-left: auto; }

Explanation:

  • The outermost container is a flex container that stretches horizontally.
  • Each "box" element is also a flex container, with its contents centered.
  • "margin-right: auto;" on the first box's inner element pushes it right against the container edge, effectively aligning it with the left side.
  • "margin-left: auto;" on the last box's inner element pulls it left to the container edge, aligning it with the right side.
  • Additional styles (e.g., height, padding) can be added for presentation purposes.

Example:

<div class="container">
  <div class="box"><div class="inner">short box</div></div>
  <div class="box"><div class="inner">centered box</div></div>
  <div class="box"><div class="inner">looooooooooooooooooooooong box</div></div>
</div>

<p>→ true center</p>

This approach aligns the middle element regardless of the widths of the side boxes, even with overflowing content.

The above is the detailed content of How to Center a Middle Item in a Flexbox Container with Uneven Side Boxes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn