background-image
、background-size
、background-repeat
的用法顏色表示法:
red
, blue
(簡單但選擇少)#3498db
(常見、精準)rgb(52,152,219)
(適合動畫或 JS 控制)hsl(204,70%,53%)
(設計直覺,方便做亮暗調整)背景控制:
background-image: url("xxx.jpg");
插入背景圖片background-size: cover;
→ 自動鋪滿,常用於 bannerbackground-size: contain;
→ 保持比例完整顯示background-repeat: no-repeat;
→ 避免重複background-position: center;
→ 控制對齊位置 <h1>CSS 顏色與背景示範</h1>
<p>這段文字使用 <strong>RGB</strong> 設定顏色。</p>
<p class="highlight">這段強調文字使用 <strong>HSL</strong>,並加上背景色。</p>
<section class="card">
<h2>卡片標題</h2>
<p>這是一個有背景圖片的卡片,並保持良好對比。</p>
</section>
</body>
</html>
/* style.css */
:root {
--primary: #3498db; /* 十六進位 */
}
* { box-sizing: border-box; }
body {
font-family: "Microsoft JhengHei", system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 24px;
color: rgb(80, 80, 80); /* RGB */
line-height: 1.6;
}
h1 {
color: var(--primary);
text-align: center;
margin-bottom: 16px;
}
.highlight {
color: hsl(0, 80%, 40%); /* HSL */
background-color: #fff3b0;
padding: 6px 8px;
border-radius: 6px;
display: inline-block;
}
.card {
width: min(92%, 340px);
margin: 24px auto;
padding: 20px;
color: #ffffff;
border-radius: 12px;
background-image: url("https://picsum.photos/640/360");
background-size: cover; /* 重要:鋪滿 */
background-repeat: no-repeat; /* 不重複 */
background-position: center; /* 置中對齊 */
box-shadow: 0 10px 20px rgba(0,0,0,0.18);
}
.card h2 {
margin: 0 0 8px;
font-weight: 700;
text-shadow: 0 1px 2px rgba(0,0,0,0.35);
}
background-size: cover/contain
background-repeat: no-repeat
background-size: cover
background-repeat: no-repeat
與 repeat-x
的差別今天開始進入到 CSS 的「顏色與背景」世界,感覺網頁終於從黑白文字變得有生命。顏色雖然看似簡單,但其實有不同的表示方式,像十六進位、RGB、HSL,各有適合的情境。特別是 HSL,很直覺地用色相、飽和度、亮度來調整,對設計來說非常方便。
背景圖片的部分讓我發現,單純插入圖片和設定背景圖片的效果完全不同。background-size: cover
能自動鋪滿區域,而 contain
則保持比例,這些細節直接影響版面的美觀與專業度。另外,背景圖片是否要重複,也能透過 background-repeat
控制,避免出現奇怪的拼貼感。
今天的練習讓我更體會到顏色不只是「好看」,而是和閱讀體驗、可讀性、甚至無障礙設計有關。未來如果能結合色彩搭配原則,應該能讓頁面更具質感。