CSS将一个项目与flexbox对齐

前端之家收集整理的这篇文章主要介绍了CSS将一个项目与flexbox对齐前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
https://jsfiddle.net/vhem8scs/

有可能有两个对齐左和一个项目对齐与flexBox?该链接更清楚地显示.最后一个例子是我想要实现的.

在flexBox中我有一个代码块.用float我有四个代码块.这就是为什么我喜欢flexBox的一个原因.

HTML

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

<!-- DESIRED RESULT -->

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

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;
}

解决方法

要将一个flex子对象与右侧对齐,请将其设置为右侧的:auto;

flex spec

One use of auto margins in the main axis is to separate flex items
into distinct “groups”. The following example shows how to use this to
reproduce a common UI pattern – a single bar of actions with some
aligned on the left and others aligned on the right.

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

Updated fiddle

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}
.wrap div:last-child {
  margin-left: auto;
}
.result {
  background: #ccc;
  margin-top: 20px;
}
.result:after {
  content: '';
  display: table;
  clear: both;
}
.result div {
  float: left;
}
.result div:last-child {
  float: right;
}
<div class="wrap">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

<!-- DESIRED RESULT -->
<div class="result">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

注意:

您可以通过在中间的flex项目(或简写flex:1)上设置flex-grow:1来实现类似的效果,这将使最后一个项目一直向右推. (Demo)

然而,明显的差异在于中间项目变得比它可能需要的更大.添加一个边框到flex项目以查看差异.

Demo

.wrap {
  display: flex;
  background: #ccc;
  width: 100%;
  justify-content: space-between;
}
.wrap div {
  border: 3px solid tomato;
}
.margin div:last-child {
  margin-left: auto;
}
.grow div:nth-child(2) {
  flex: 1;
}
.result {
  background: #ccc;
  margin-top: 20px;
}
.result:after {
  content: '';
  display: table;
  clear: both;
}
.result div {
  float: left;
}
.result div:last-child {
  float: right;
}
<div class="wrap margin">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

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

<!-- DESIRED RESULT -->
<div class="result">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>
原文链接:https://www.f2er.com/css/216603.html

猜你在找的CSS相关文章