【HTML、CSS教學】9. 圖片引用

Neptune Li
Li-NInja
Published in
3 min readFeb 14, 2020

🚩圖片引用

以下會舉例一些圖片引用的方法,以及運用的技巧。

① 寫在img標籤裡

直接將要載入的圖片路徑放進img標籤裡面。

<img src=”http://lorempixel.com/200/200/food/" alt=””>

② 寫在div標籤的CSS

使用background-image來載入圖片,
這邊要注意的是,需要使用 background-repeat: no-repeat
否則瀏覽器會依照div的寬度,重複使用圖片來占滿div空間。

background-repeat的用法總共有四種:

  1. repeat →依照div的大小將圖片依x軸、y軸重複呈現。
  2. repeat-x →依照div的大小將圖片依x軸重複呈現。
  3. repeat-y →依照div的大小將圖片依y軸重複呈現。
  4. no-repeat →圖片不重複出現
<style>
.box2 {
background-image: url(‘http://lorempixel.com/200/200/food/');
height: 200px;
background-repeat: no-repeat;
}
</style>
<h2>box2 的圖片</h2>
<div class=”box2"></div>

③ 利用repeat的方式顯示背景顏色

利用repeat的方式,可以填滿背景色彩。在設計一些網頁背景樣式時就能夠減少檔案的大小,以提升網頁載入的速度。

<style>
.box2 {
background-image: url('https://i.imgur.com/uYokA22.png');
height: 405px;
width: 400px;
}
</style>
<h2>box3 利用repeat的方式顯示背景顏色</h2>
<div class=”box3"></div>

④ 官網banner的運用

一般官網的 banner 尺寸多為長方形,有固定的高度以及自適應裝置的寬度,此時可以使用 position 的方式將圖片重點部分為中心來顯示該圖片。

使用 backgrund-size ,讓圖片可以根據容器的大小自適應放大。

<style>
.box4 {
background-image: url('https://images.unsplash.com/photo-1578212631165-654917de6257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
height: 400px;
background-position: center center;
background-size: cover;
}
</style>
<h2>box4 官網banner的運用</h2>
<div class="box4"></div>

🚩範例CodePen

--

--