css文件 如何使背景图片大小适应div的大小

html-css016

css文件 如何使背景图片大小适应div的大小,第1张

需要准备的材料分别有:电脑、浏览器、html编辑器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<style>标签中,输入css代码:

div{width: 300pxheight: 150pxbackground-image: url(small3.png)background-size: 100%}

3、浏览器运行index.html页面,此时背景图片充满了div的大小。

onload=function(){

var imgs=document.querySelectorAll("div>img")

for(var i = 0i <imgs.lengthi++){

var img = imgs[i]

var p = img.parentElement

p.style.width = img.offsetWidth * 192 / 150 + "px"

p.style.height = img.offsetHeight * 128 / 100 + "px"

}

}

使用背景属性即可;

背景属性为background;

给div添加style样式:background-image

使用绝对或相对 url 地址指定背景图像

设置或检索对象的背景图像。当背景图像与背景颜色( background-color

)都被设定了时,背景图片将覆盖于背景颜色之上

此属性对于 currentStyle 对象而言是只读的。对于其他对象而言是可读写的。对应的脚本特性为

backgroundImage

代码示例:

BODY { background-image: url("marble.gif") }         

P { background-image: none }        

div { background-image: url("comet.jpg") }       

blockquote { background-image: url("c:\InetPub\MyPixs\comet.jpg") }        

span { background-image: url(

) }