Home > Web Front-end > CSS Tutorial > How to Align a Single Element to the Right Using Flexbox?

How to Align a Single Element to the Right Using Flexbox?

Linda Hamilton
Release: 2024-12-16 02:16:17
Original
824 people have browsed it

How to Align a Single Element to the Right Using Flexbox?

Aligning One Item Right with Flexbox

To address the question of aligning one element right within a flexbox layout, the HTML and CSS codes provided showcase a basic flexbox setup that positions two items left and one item right within a container.

HTML

<div class="wrap">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

<div class="result">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
Copy after login

CSS

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}

.result {
  background: #ccc;
  margin-top: 20px;
}

.result:after {
  content: '';
  display: table;
  clear: both;
}

.result div {
  float: left;
}

.result div:last-child {
  float: right;
}
Copy after login

Flexbox Approach

To align one child element right, set it with margin-left: auto;. This leverages the auto margin property in the main axis, which is useful for separating flex items into distinct groups.

.wrap div:last-child {
  margin-left: auto;
}
Copy after login

Updated Fiddle

An updated JSFiddle demonstrates this approach effectively:

[Updated Fiddle](https://jsfiddle.net/vhem8scs/)

In the updated CSS, the margin-left: auto; property is applied to the last div element within the .wrap container, causing it to align right.

The above is the detailed content of How to Align a Single Element to the Right Using Flexbox?. 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