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(繼承自父層的屬性)
position
relative
- 在原本的位置上設定 left/right/top/bottom 偏移(起始)
- 原本的位置還在
- 設定
z-index
控制元素是否在第一層- 設定 relative 也可以讓元素浮起
1 | position: relative; |
fixed
- 完全浮起來,原本的位置會被後面的元素佔走
- 從螢幕的最上面開始計算偏移 left/right/top/bottom
- 固定在螢幕上,上下滑動時還在
1 | position: fixed; |
absolute
- 跟 fixed 一樣會浮起來,位置被其他元素佔走
- 根據外層(有定位者)偏移
- left/right/top/bottom
- 會固定在畫面上,往下滑動時會看不見
1 | position: absolute; |
- 元素置中
- 在父元素設定相對定位(relative)
- 設定
top: 50%
left:50%
- 要置中的元素設定絕對定位(absolute)
- 設定
transform: translate(-50%, -50%);
tanslate(x軸, y軸)