點燈坊

失くすものさえない今が強くなるチャンスよ

使用 background 顯示圖片

Sam Xiao's Avatar 2021-01-23

background 本質雖然是定義背景圖片,但也可用來取代 <img>,讓我們以 CSS 設定圖片。

Version

CSS 3

img

bgimg000

傳統欲顯示圖片會使用 <img>

<template>
  <img src="https://picsum.photos/300/200/?random=10">
</template>

<img> 為 HTML tag,需使用 src attribute 設定圖片位置。

傳統必須在 HTML 設定圖片位置,是否能在 CSS 設定呢 ?

div

<template>
  <div class="scenery"/>
</template>

<style scoped>
.scenery {
  background: url(https://picsum.photos/320/240/?random=10);
  width: 320px;
  height: 240px;
}
</style>

第 2 行

<div class="scenery"/>

雖然顯示圖片,但卻使用 <div>

第 6 行

.scenery {
  background: url(https://picsum.photos/320/240/?random=10);
  width: 320px;
  height: 240px;
}
  • background:使用 url() 定義 <div> 所使用圖片,重點在於能在 CSS 定義圖片
  • widthheightbackground-image<img> 不同,並無法自行撐出 width 與 height,而是由 parent element 決定,因此要自行定義 width 與 height
<template>
  <div class="scenery"/>
</template>

<style scoped>
.scenery {
  background: url(https://picsum.photos/320/240/?random=10) no-repeat;
  height: 240px;
}
</style>

若不想指定 width,則要使用另外一種寫法。

10 行

.scenery {
  background: url(https://picsum.photos/320/240/?random=10) no-repeat;
  height: 240px;
}
  • background:加特別上 no-repeat
  • height:因為 <div> 為 block element,其 width 為一整列,但 height 由 content 決定,目前 <div> 沒有 content,必須指定 height 才能顯示 background 所指定圖片

img

<template>
  <img class="scenery">
</template>

<style scoped>
.scenery {
  background: url(https://picsum.photos/320/240/?random=10);
  width: 320px;
  height: 240px;
}
</style>

其實 background-image 也可套用在 <img>

第 6 行

.scenery {
  background: url(https://picsum.photos/320/240/?random=10);
  width: 320px;
  height: 240px;
}
  • background<img> 也使用 background
  • widthheight<img> 為 inline element,並不像 <div> 有 width,因此 widthheight 都要設定

Conclusion

  • <img> 可根據圖片自行撐出 width 與 height,但 background 則必須在 parent child 指定 widthheight
  • background 可用於 <div><img>,唯 <div> 是 block element,因此可不用設定 height,但 <img> 是 inline element,需同時指定 widthheight

Reference

MDN, background