background Property 需搭配 url(),也可使用 CSS Variable。
Version
CSS 3
div

在 <div> 使用 background 顯示圖片。
<template>
<div class="scenery"/>
</template>
<style scoped>
* {
--image: url(https://picsum.photos/320/240/?random=10)
}
.scenery {
background: var(--image);
width: 320px;
height: 240px;
}
</style>
第 2 行
<div class="scenery"/>
雖然顯示圖片,但 HTML 只使用了 <div>。
第 6 行
* {
--image: url(https://picsum.photos/320/240/?random=10)
}
--image:使用url()定義圖片位置
10 行
.scenery {
background: var(--image);
width: 320px;
height: 240px;
}
background:定義<div>所使用的圖片,可直接使用--imagewidth與height:background與<img>不同,並無法自行撐出 width 與 height,而是由 parent element 決定,因此要自行定義 width 與 height
Conclusion
backgroundproperty 實務上經常搭配url()與 CSS variable 使用