Home > Web Front-end > CSS Tutorial > How to Align One Element Left and Another Center with Flexbox Without Absolute Positioning?

How to Align One Element Left and Another Center with Flexbox Without Absolute Positioning?

Patricia Arquette
Release: 2024-10-26 15:07:30
Original
954 people have browsed it

How to Align One Element Left and Another Center with Flexbox Without Absolute Positioning?

Aligning Left and Center with Flexbox: A Solution without Absolute Positioning

When using flexbox for aligning child elements, it can be challenging to align one element to the left and center the other without using absolute positioning. Here's a solution that uses an additional empty element:

HTML:

<code class="html"><div class="parent">
  <div class="left">Left</div>
  <div class="center">Center</div>
  <div class="right"></div>
</div></code>
Copy after login

CSS:

<code class="css">.parent {
  display: flex;
}

.left,
.right {
  flex: 1;
}

/* Styles for demonstration */
.parent {
  padding: 5px;
  border: 2px solid #000;
}

.left,
.right {
  padding: 3px;
  border: 2px solid red;
}

.center {
  margin: 0 3px;
  padding: 3px;
  border: 2px solid blue;
}</code>
Copy after login

Explanation:

  1. The left and right elements are set to flex: 1, which makes them grow to equally distribute the available space.
  2. The empty right element guarantees that the left element will not push the center element off center.

This approach creates a consistent and centered alignment without the need for absolute positioning or duplicating the left content on the right.

The above is the detailed content of How to Align One Element Left and Another Center with 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