萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 實戰:div 容器常用樣式屬性完整配置指南

div 核心樣式屬性速查

<div> 作為最常用的佈局容器,掌握其高頻 CSS 屬性組合能大幅提升開發效率。本文整理實戰中最常用的屬性配置,含語法、取值範圍與注意事項。

1. 尺寸與溢出控制

屬性說明常用值/範例
width / height寬/高度300px, 50%, auto, min/max-width
overflow內容溢出處理visible(默認) | hidden | scroll | auto
overflow-x / overflow-y單向溢出控制同 overflow

2. 盒模型:邊距、邊框、內距

屬性說明語法範例
margin外邊距margin: 10px 20px; (上下 左右) / margin: 10px 20px 15px 5px; (上 右 下 左)
padding內邊距同 margin 語法,無負值
border邊框簡寫border: 1px solid #ccc;
border-radius圓角border-radius: 8px; / 50% (圓形)
box-shadow陰影box-shadow: 0 2px 8px rgba(0,0,0,.1);

注意: padding 與 border 會增加元素實際佔用尺寸(除非設定 box-sizing: border-box)。

3. 文字與字體樣式

屬性說明常用值
color文字顏色#333, rgb(51,51,51), var(--text-color)
font-size字號14px, 1rem, 0.875rem
font-family字體族"PingFang SC", "Microsoft YaHei", sans-serif
font-weight粗細400(normal), 700(bold), 300/500/600
line-height行高1.5, 1.6 (無單位推薦)
text-align水平對齊left, center, right, justify

4. 背景樣式

屬性說明範例
background-color背景色#f5f5f5, rgba(0,0,0,.05)
background-image背景圖url(/img/bg.png), linear-gradient(45deg, #fff, #eee)
background-repeat平鋪no-repeat, repeat-x, repeat-y
background-position定位center, top right, 10px 20px
background-size尺寸cover, contain, 100% auto
background-attachment固定/滾動scroll(默認), fixed(視差效果)
background簡寫background: #fff url(...) no-repeat center / cover;

5. 定位與堆疊

屬性說明關鍵值
position定位類型static(默認) | relative | absolute | fixed | sticky
top/right/bottom/left偏移量配合非 static 定位使用
z-index堆疊層級整數,僅對定位元素生效
display顯示模式block, flex, grid, none(隱藏)

6. 進階視覺效果

屬性說明範例
opacity整體透明度0.5 (0-1),子元素同步透明
filter濾鏡效果blur(4px), grayscale(100%), drop-shadow(...)
transform2D/3D 變形translateX(10px), rotate(45deg), scale(1.1)
transition過渡動畫all 0.3s ease
cursor滑鼠樣式pointer, text, move, not-allowed

7. 文字換行與截斷

.text-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis; /* 單行省略號 */
}

.text-clamp-3 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 多行省略,需配合 */
  overflow: hidden;
}

8. 滾動條樣式(WebKit 內核)

::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: #f1f1f1; }
::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #555; }

9. 書寫方向與斷詞

屬性說明值
direction文字方向ltr(默認), rtl
word-break斷詞規則normal, break-all, keep-all
word-wrap / overflow-wrap長詞換行break-word, anywhere
writing-mode排版方向horizontal-tb, vertical-rl, vertical-lr

實戰最佳實踐建議

  1. 重置默認樣式: 統一使用 box-sizing: border-box,配合 Normalize.css 或現代 Reset。
  2. 佈局優先 Flex/Grid: 減少 float、position 絕對定位,提升維護性。
  3. 響應式單位: 寬度用 %、字體用 rem、間距用 em/rem,配合媒體查詢。
  4. 語義化類名: 如 .container, .row, .col, .card,避免 .red-box 等表現類名。
  5. 性能考量: 避免過度使用 box-shadow、filter、大面積 fixed 定位,移動端啟用 GPU 加速需謹慎。
copyright © 萬盛學電腦網 all rights reserved