Layout (佈局)
- 對應螢幕的客製化佈局
- 常用的排版屬性
- 位移
- 大小
- width
- min-width
- max-width
- height
- min-height
- max-height
- 邊距
- 邊框
- box-sizing
- 溢出控制
- 深度
- 動畫效果
- 自適應佈局 (Responsive Layout)
- 通過
@media 來設計不同螢幕的尺寸佈局
/* 手機裝置樣式 */
@media (max-width: 768px) {
/* 手機螢幕的樣式 */
}
/* PC 裝置樣式 */
@media (min-width: 769px) {
/* PC 螢幕的樣式 */
}
display
none
- 使元素完全從頁面上移除,不佔據任何空間
- 常見於需要暫時隱藏內容的場景
block
- 以新的一行佔據父容器整個寬度
- 常見如
<div>、<p>、<h1>-<h6>、<section>
flex
- 使元素成員彈性盒子容器 (flex container)
- 使用
flex 屬性排列的 display:block
grid
- 使元素成為一個網格容器 (grid container)
- 使用
grid 屬性定義列與行的 display:block
inline
- 作為行內元素顯示,只占據內容所需的寬度
- 常見如
<span>、<a>、<em>、<strong>
inline-block
- 如同
inline,但允許設置 windth、height
- 常見如需要控制大小,但不需要佔據整行的元素 (導航欄的按鈕)
inline-flex
- 元素作為行內元素顯示,但允許使用
flex 控制子元素
inline-grid
- 元素作為行內元素顯示,但允許使用
grid 控制子元素
table
- 使元素表現像
<table> 表格容器
- 內部元素可使用
display:table-row、display:table-cell
table-row
- 模擬表格中的行,用於包含
display:table-cell 元素
table-cell
contents
- 讓元素本身被忽略,但是子元素正常保留
- 常用於需要包裝資料,但不想影響佈局的
<div>
list-item
position
- 用於控制元素在頁面中的定位方式
- 會搭配 top、right、bottom、left 使用
static
- 不會特別被定位
- 會保留在文檔流
- 按照瀏覽器預設自動排版
- 無法使用 top、right、bottom、left 屬性做微調
relative
- 原始位置與 static 一樣
- 會保留在文檔流
- 允許使用 top、right、bottom、left 等屬性微調
- 允許使用 width、height 等屬性微調
.relative-element {
position: relative;
top: 10px; /* 向下移動 10 px */
}
absolute
- 以父層元素的相對位置做定位
- 若父層元素沒有非 static 的,就以 body 定位
- 會脫離文檔流的空間,被其他元素忽略
- 常用於彈出視窗、圖層效果等
.absolute-element {
position: absolute;
top: 50px; /* 參考父元素的上方邊緣 */
left: 30px; /* 參考父元素的左側邊緣 */
}
fixed
- 位置不受滾動影響,且始終相對於視窗定位
- 會脫離文檔流的空間,被其他元素忽略
- 允許使用 top、right、bottom、left 等屬性微調
- 允許使用 width、height 等屬性微調
- 常用於導航欄、工具欄、返回頂部按鈕
.fixed-element {
position: fixed;
bottom: 0; /* 固定在視窗的下方 */
right: 0; /* 固定在視窗的右側 */
}
sticky
- 黏性定位,結合 relative、fixed 的特點
- 當元素跨越指定邊界時,會變為固定位置
- 常用於滾動過程中需要特定位置懸停,例如表格的標頭
.sticky-element {
position: sticky;
top: 0; /* 當滾動到距離頂部 0px 時變為固定位置 */
}
Flexbox 佈局
- 啟用彈性佈局
- display: flex
- display: inline-flex
父層設置
flex-direction
- 控制主軸方向
- row:水平由左到右排列 (預設)
- row-reverse:水平由右到左
- column:垂直從上到下
- column-reverse:垂直從下到上
flex-wrap
- 子元素是否換行
- nowrap:不換行 (預設)
- wrap:需要時換行
- wrap-reverse:需要時換行,但反向排列行順序
justify-content
- 沿主軸對齊的方式
- flex-start
- flex-end
- center
- space-between
- space-around
align-items
- 交叉軸對齊方式
- flex-start
- flex-end
- center
- stretch
align-content
子層設置
order
flex-grow
flex-shrink
flex-basis
flex
align-self
Grid 佈局
grid-template-columns
grid-template-rows
grid-column
grid-row
gap
justify-items
align-items
grid-template-areas