float

  • 常見區塊(block)元素標籤:div、ul li、p、h1

    • 元素寬度預設會撐到最大,使其占滿整個容器
    • 可以設定長寬/margin/padding,但仍會占滿一整行
  • 常見行內(inline)元素標籤:span、a、input、img

    • 元素可在同一行內呈現,圖片或文字均不換行,也不會影響其版面配置
    • 不可設定長寬,元素的寬高由它的內容撐開
  • display: inline-block;

    • inline 屬性但可以設定寬高、margin、padding
  • 文繞圖效果(block 變成 inline)

    • float: 浮動方向;
    • clear: both;清除浮動
      • left(靠左浮動)
      • right(靠右浮動)
      • none(預設值,也就是不浮動)
      • inherit(繼承自父層的屬性)
  • float 示意圖

position

relative

  • 在原本的位置上設定 left/right/top/bottom 偏移(起始)
  • 原本的位置還在
  • 設定 z-index 控制元素是否在第一層
    • 設定 relative 也可以讓元素浮起
1
2
3
4
position: relative;
left: 120px; /* 由左往右120px */
top: 10%; /* 由上往下 父層寬度10% */
z-index: auto; /* auto < 1 < 2... */

fixed

  • 完全浮起來,原本的位置會被後面的元素佔走
  • 從螢幕的最上面開始計算偏移 left/right/top/bottom
    • 固定在螢幕上,上下滑動時還在
1
2
3
4
5
6
7
8
9
10
11
12
13
14
position: fixed;
/* 定在左上角 */
left: 0;
top: 0;

/* 定在畫面正中間 */
position: fixed;
margin: auto;
inset: 0;
/* inset 相等於:
right: 0;
bottom: 0;
left: 0;
top: 0;*/

absolute

  • 跟 fixed 一樣會浮起來,位置被其他元素佔走
  • 根據外層(有定位者)偏移
    • left/right/top/bottom
    • 會固定在畫面上,往下滑動時會看不見
1
2
3
position: absolute;
left: 0;
top: 0;
  • 元素置中
    • 在父元素設定相對定位(relative)
    • 設定top: 50% left:50%
    • 要置中的元素設定絕對定位(absolute)
    • 設定transform: translate(-50%, -50%);
      • tanslate(x軸, y軸)