Home  >  Article  >  Web Front-end  >  How to Align Elements Left and Center in Flexbox Without Absolute Positioning?

How to Align Elements Left and Center in Flexbox Without Absolute Positioning?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 21:01:01329browse

How to Align Elements Left and Center in Flexbox Without Absolute Positioning?

Aligning Elements Left and Center with Flexbox

Problem:

Align child elements within a flexbox container, with one element centered and the other aligned to the left.

Code:

#parent {
  align-items: center;
  border: 1px solid black;
  display: flex;
  justify-content: center;
  margin: 0 auto;
  width: 500px;
}
#left {
  margin-right: auto;
}
#center {
  margin: auto;
}

Issue:

Using margin-right: auto pushes the centered element off-center.

Solution without Absolute Positioning:

Add a third empty element:

<div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div>

Apply the following styles:

.parent {
  display: flex;
}
.left, .right {
  flex: 1;
}

Explanation:

Both left and right are set to grow (flex: 1), evenly distributing the available space. Since the empty right element has the same width as left, the center element remains perfectly centered.

Benefits of this Solution:

  • No need to copy content between elements.
  • Perfectly centered element, regardless of content width.

The above is the detailed content of How to Align Elements Left and Center in Flexbox Without Absolute Positioning?. 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