Home >Web Front-end >CSS Tutorial >How Can I Center a Middle Element Between Dynamically Sized Sibling Elements?

How Can I Center a Middle Element Between Dynamically Sized Sibling Elements?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 10:27:13756browse

How Can I Center a Middle Element Between Dynamically Sized Sibling Elements?

Centering the Middle Element with Dynamic Sibling Widths

Imagine a layout consisting of three boxes horizontally aligned with dots representing the spacing between them:

[Left box]......[Center box]......[Right box]

When one of the side boxes is removed, the center box should remain centered:

[Left box]......[Center box].................

And likewise when the other side box is removed:

................[Center box].................

Additionally, the center box content should expand to fill available space, while the side boxes remain fixed in size. Overflow will be handled with overflow: hidden and text-overflow: ellipsis to clip the content.

[Left box][Center boxxxxxxxxxxxxx][Right box]

While a flexbox structure aligns elements horizontally, it does not maintain centering when side boxes have different widths. To achieve the desired effect, we introduce nested flex containers and auto 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; }

This strategy uses auto margins to automatically center the middle item, regardless of the width of the side boxes. The justify-content: center; alignment ensures that the content within the middle box remains centered.

By nesting flex containers, we limit the margins to the individual boxes, preventing them from affecting the layout of other elements. This method achieves true centering even when the widths of the side boxes differ significantly.

The above is the detailed content of How Can I Center a Middle Element Between Dynamically Sized Sibling Elements?. 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