css flex佈局中妙用margin: auto

在使用Flex佈局時僅使用align-itemsjustify-content有時並不能知足咱們的須要,經過margin: auto咱們能夠實現一些比較有用的佈局。css

咱們先弄一個小demo, 下面的例子都是基於這個demo作修改html

<div id="container">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
</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中查看 spring

margin-right: auto

.box5 {
    margin-left: auto;
}
複製代碼

在jsfiddle中查看 bash

上面的例子並不限於一個元素佈局

.box2 {
  margin-right: auto;
}
複製代碼

在jsfiddle中查看 flex

2. 不同的space-between

.box1 {
  margin-right: auto;
}
.box5 {
  margin-left: auto;
}
複製代碼

在jsfiddle中查看 flexbox

3. 不同的space-around

.box1, .box4 {
  margin-left: auto;
}
.box2, .box5 {
  margin-right: auto;
}
複製代碼

在jsfiddle中查看 spa

4. 放置於角落

.box5 {
  align-self: flex-end;
  margin-left: auto;
}
複製代碼

在jsfiddle中查看 .net

參考文章:code

  1. In CSS Flexbox, why are there no 「justify-items」 and 「justify-self」 properties?
相關文章
相關標籤/搜索