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
Release: 2024-12-19 20:45:10
Original
264 people have browsed it

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; }
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template