iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 6
0
自我挑戰組

如何成為工程師? (從工地到前端工程師)系列 第 6

[Day 6] CSS Flexbox

CSS排版一直是一件很幹的事. 從最一開始是用table 然後換到float, 這些屬性都不是專門為排版而設計的。現在CSS推出 flexbox(未來還有grid) 來解決我們排版的問題了。 woohoo.

justify-content
flex-grow
flex-direction

flexbox 主要有兩個元件, 一個爸爸(parent) 一個小孩(child). 爸爸元件可以決定方向,換行/單行, 平行位置, 垂直位置 , 塞滿或空間區隔. 以下是爸爸的屬性。

  • flex-direction方向,確定 main axis 是平行還是垂直
  • flex-wrap換行/單行
  • flex-flow 簡寫 flex-direction + flex wrap
  • justify-content main axis 位置
  • align-items cross axis 位置
  • align-content塞滿或空間區隔

這是小孩(child) 的屬性。

  • order 順序
  • flex-grow 決定大
  • flex-shrink 決定小
  • flex-basis 確定寬度,基本上跟width一樣
  • flex 簡寫 flex-grow, flex-shrink, and flex-basis
  • align-self 決定位子 (align-self 屬性覆蓋 爸爸align-items 預設的屬性)

教學應用

廢話少說, 我們來做一個響應式的導航欄(responsive navbar). Let's do ittttt!

<!-- 我這裡有用font-awesome  -->
<nav>
 <a href=""><i class="fa fa-home"></i>Home</a>
 <a href=""><i class="fa fa-question"></i>About</a>
 <a href=""><i class="fa fa-phone"></i>Contact</a>
 <a href=""><i class="fa fa-paw"></i>Dogs</a>
</nav>
nav {
  display: flex; // 我們先讓nav元件變成flex 
  flex-direction: row; // 方向平行
  justify-content: flex-end; // 位子偏右邊
}

a {
  font-size: 40px;
  text-decoration: none;
  color: #95a5a6;
  font-family: raleway;
  border-bottom: 1px solid #52c9aa;
  margin: 20px;
  transition: color 0.5s ease-out;
}

a:hover {
  color: #3498db;
  border-bottom-color: #3498db;
}

i {
  margin-right: 10px;
}

// 平板的css
@media screen and (max-width: 920px) {
  nav {
    justify-content: space-between; //每一個區塊要有區間
  }
  a {
    font-size: 25px;
  }
}

// 手機的css
@media screen and (max-width: 600px) {
  nav {
    flex-direction: column; //方向變垂直!
    align-items: center; //cross-axis 中間
  }
}

連結codepen
https://ithelp.ithome.com.tw/upload/images/20171209/20107433aRHQfVQtvb.png
https://ithelp.ithome.com.tw/upload/images/20171209/201074338f0u025rZG.png

https://ithelp.ithome.com.tw/upload/images/20171209/20107433FFz5zo4s01.png

參考連結


上一篇
[Day 5] CSS Animation , 讓網頁動起來
下一篇
[Day 7 ] JS 電腦思維,軟體規劃
系列文
如何成為工程師? (從工地到前端工程師)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言