css给未知宽高的元素添加背景图片
给页面的某一元素添加背景图片,当没有指定具体的宽高时,是无法显示效果的
1、添加背景图
HTML代码:
<!DOCTYPEhtml><html><headlang="en"><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><metaname="format-detection"content="telephone=no"/><metaname="format-detection"content="email=no"/><title></title><style>*{margin:0;padding:0;}#wrap{width:100%;height:auto;background:url('p_w_picpaths/page.jpg')no-repeatcentercenter;background-size:cover;}</style></head><body><divid="wrap"></div></body></html>
我们可以看看页面效果截图:
为了达到适应不同终端的屏幕大小,我们又不能把宽高写死,那怎么办呢?可以采取以下方法:
HTML代码:
<!DOCTYPEhtml><html><headlang="en"><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><metaname="format-detection"content="telephone=no"/><metaname="format-detection"content="email=no"/><title></title><style>*{margin:0;padding:0;}#wrap{width:100%;height:100%;background:url('p_w_picpaths/page-small.jpg')no-repeat;background-size:cover;position:fixed;z-index:-10;background-position:00;}</style></head><body><divid="wrap"></div></body></html>
再来看看页面效果:
手机页面效果
注意:如果去掉div,直接把样式加在body上面的话,在PC端浏览器可以显示,安卓手机里面也可以显示,但是在苹果手机里面就无法显示。多次反复测试,均重现此bug(如有朋友遇到此类问题的正解,欢迎指教!)
(上图为苹果机型下的截图)
2、通过img标签添加背景图
HTML代码:
<!DOCTYPEhtml><html><headlang="en"><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><metaname="format-detection"content="telephone=no"/><metaname="format-detection"content="email=no"/><title></title><style>*{margin:0;padding:0;}</style></head><body><divid="wrap"><imgclass="imgBcground"src="p_w_picpaths/page-small.jpg"alt=""></div></body></html>
查看页面效果时发现,图片是以百分百实际大小呈现,显然不是我们想要的效果
跟上面的例子很相像,我们只需要稍加修改就好
HTML代码:
<!DOCTYPEhtml><html><headlang="en"><metacharset="UTF-8"><metaname="viewport"content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/><metaname="format-detection"content="telephone=no"/><metaname="format-detection"content="email=no"/><title></title><style>*{margin:0;padding:0;}.imgBcground{display:block;width:100%;height:100%;position:fixed;z-index:-10;}</style></head><body><divid="wrap"><imgclass="imgBcground"src="p_w_picpaths/page-small.jpg"alt=""></div></body></html>
在不同模拟机型下查看页面效果均可以实现:
关于background-size属性,W3C是这么定义的
具体可以查看链接:http://www.w3school.com.cn/c***ef/pr_background-size.asp
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。