1. 程式人生 > 實用技巧 >CSS 06 背景

CSS 06 背景

示例1:

背景顏色

屬性名background-color
顏色的值可以採用3種方式
1. 預定義的顏色名字
比如red,gray,white,black,pink,參考顏色速查手冊
2. rgb格式
分別代表紅綠藍的比例 rgb(250,0,255) 即表示紅色是滿的,沒有綠色,藍色是滿的,即紅色和藍色混合在一起:紫色
3. 16進位制的表示
#00ff00 等同於 rgb(0,255,0)

<style>
p.gray {background-color: gray;}
h1 {background-color: transparent}
h2 {background-color: rgb(250,0,255)
} h3 {background-color: #00ff00} </style> <p class="gray">灰色</p> <h1>透明背景,預設即透明背景</h1> <h2>紫色</h2> <h3>綠色背景</h3>

示例2:

圖片做背景

<style>
div#test
  {
    background-image:url(/study/background.jpg);
    width:200px;
    height:100px;
  }
</style>
<div id="test"> 這是一個有背景圖的DIV </div>

示例3:

本地測試

在本地測試的時候,請先從右側下載圖片
不要寫成background-image:url(/study/background.jpg);
而是寫成 background-image:url(background.jpg);
並且把圖片和html檔案放在同一個目錄下

示例4:

背景重複

background-repeat屬性
值可以選
repeat; 水平垂直方向都重複
repeat-x; 只有水平方向重複
repeat-y; 只有垂直方向重複
no-repeat; 無重複

<
style> div#norepeat { background-image:url(/study/background_small.jpg); width:200px; height:100px; background-repeat: no-repeat; } div#repeat-x { background-image:url(/study/background_small.jpg); width:200px; height:100px; background-repeat: repeat-x; } </style> <div id="norepeat"> 背景不重複 </div> <div id="repeat-x"> 背景水平重複 </div>

示例5:

背景平鋪

屬性:background-size
值:contain

<style>
div#contain
  {
    background-image:url(/study/background_small.jpg);
    width:200px;
    height:100px;
    background-size: contain;
  }
</style>
  
<div id="contain">
   背景平鋪,通過拉伸實現,會有失真
</div>