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

Barbara Streisand
Release: 2024-10-27 21:01:01
Original
328 people have browsed it

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

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

Apply the following styles:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!