# background-img 用法
###### tags: `CSS` `background` `網頁切版直播班 - 2021 夏季班` `切版直播班`
### background-repeat:將圖片重複顯示,repeat-x
* 切成小圖,使用 x 軸 repeat
* 背景圖小、載入速度快,以提升使用者體驗
```
.box {
width: 1003px;
height: 405px;
background-image: url(./images/bg-s.png);
background-repeat: repeat-x;
}
```
### background-color:與背景圖片的混用
* 用法:讓背景高度自適應延伸 → 不寫死高度
```
讓背景高度自適應延伸→不寫死高度
.box {
width: 1003px;
/* height: 405px; */
/* 讓背景高度自適應延伸 => 不寫死高度 */
background-image: url(./images/bg-s.png);
background-repeat: repeat-x;
/* x軸重複 */
background-color: #02976f;
/* 吸取漸層最底部顏色 */
}
```
### background-position:移動 background 的位置
* background-position 定位
1. 可直接寫方位 ex. left top ex. right bottom
1. 可指定數值 ex. 30px 30px
1. 可指定%數 ex. 90% 90%
```
.content {
margin-top: 50px;
width: 400px;
height: 500px;
background-color: #eee;
background-image: url(https://ithelp.ithome.com.tw/storage/image/logo.svg);
background-repeat: no-repeat;
background-position:
/* 指定方位 left top bottom right */
/* right bottom; */
/* 數值:左距/上距 */
/* 30px 30px; */
/* %數:x軸移動~%位置/y軸移動~%位置 */
90% 90%;
}
```
### background 縮寫
* 可將其中所有屬性 寫進同一行內
統稱寫法為 **background**:
```
.content {
margin-top: 50px;
width: 400px;
height: 500px;
background: url(https://ithelp.ithome.com.tw/storage/image/logo.svg) no-repeat pink 90% 90%;
}
```
### 圖片取代文字技巧 - 以 logo 為例
* 業界常用的 3 行技巧
```
.header h1 a {
text-indent: 101%; 首行的縮排
overflow: hidden; 超出 div 範圍就隱藏
white-space: nowrap; 希望都可在第一行,不斷行
}
```

### 圖片種類介紹 ( gif、jpg、png )
* gif 有透明效果,有動畫效果,只有256色
* jpg 沒有透明效果
* png8 只支援256色
* png24 有透明效果(漸層效果)
### background-size: cover 語法
```
.banner {
height: calc(100vh - 50px); /* 扣掉上面.header的50px高度 */
background: url(...) center; /* 圖片水平垂直置中 */
background-size: cover; /* 背景自適應延伸屬性 */
}
```
[Codepen練習](https://codepen.io/Zoechiueh/pen/yLbawxO?editors=1100)
[影片教學](https://youtu.be/1EYUsAlVqY0?t=631)
### img 與 background-img 使用時機
* background-img
→ 裝飾用途,跟資料庫沒有關係可於 CSS 寫死
ex. 網站 logo (固定不換)
```
.banner {
background: url(../png) no-repeat center;
}
```
* img 標籤
→ 動態網頁:動態產生的資料,連動資料庫
HTML上先設空值,待後端資料庫整合回傳的資料
ex. pchome 產品列表
ex. 客戶後台上稿資料