css flex布局中妙用margin: auto

在使用Flex布局时仅使用align-itemsjustify-content有时并不能满足我们的需要,通过margin: auto我们可以实现一些比较有用的布局。

我们先弄一个小demo, 下面的例子都是基于这个demo做修改

<div id="container">
  <div class="box box1">1div>
  <div class="box box2">2div>
  <div class="box box3">3div>
  <div class="box box4">4div>
  <div class="box box5">5div>
div>
复制代码
#container {
  display: flex;
  justify-content: flex-end;
  background-color: lightyellow;
}
.box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 75px;
  background-color: springgreen;
  border: 1px solid #333;
}
复制代码

1. 不一样的两端对齐

.box1 {
    margin-right: auto;
}
复制代码

在jsfiddle中查看

.box5 {
    margin-left: auto;
}
复制代码

在jsfiddle中查看

上面的例子并不限于一个元素

.box2 {
  margin-right: auto;
}
复制代码

在jsfiddle中查看

2. 不一样的space-between

.box1 {
  margin-right: auto;
}
.box5 {
  margin-left: auto;
}
复制代码

在jsfiddle中查看

3. 不一样的space-around

.box1, .box4 {
  margin-left: auto;
}
.box2, .box5 {
  margin-right: auto;
}
复制代码

在jsfiddle中查看

4. 放置于角落

.box5 {
  align-self: flex-end;
  margin-left: auto;
}
复制代码

在jsfiddle中查看

参考文章:

  1. In CSS Flexbox, why are there no “justify-items” and “justify-self” properties?

你可能感兴趣的:(css flex布局中妙用margin: auto)