给页面的某一元素添加背景图片,当没有指定具体的宽高时,是无法显示效果的
1、添加背景图
HTML代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="format-detection" content="email=no"/>
<title></title>
<style>
*{margin:0; padding:0;}
#wrap{
width:100%;
height:auto;
background:url('images/page.jpg') no-repeat center center;
background-size:cover;
}
</style>
</head>
<body>
<div id="wrap">
</div>
</body>
</html>我们可以看看页面效果截图:

立即学习“前端免费学习笔记(深入)”;
为了达到适应不同终端的屏幕大小,我们又不能把宽高写死,那怎么办呢?可以采取以下方法:
HTML代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="format-detection" content="email=no"/>
<title></title>
<style>
*{margin:0; padding:0;}
#wrap{
width:100%;
height:100%;
background:url('images/page-small.jpg') no-repeat;
background-size:cover;
position:fixed;
z-index:-10;
background-position:0 0;
}
</style>
</head>
<body>
<div id="wrap">
</div>
</body>
</html>再来看看页面效果:

手机页面效果

注意:如果去掉div,直接把样式加在body上面的话,在PC端浏览器可以显示,安卓手机里面也可以显示,但是在苹果手机里面就无法显示。多次反复测试,均重现此bug(如有朋友遇到此类问题的正解,欢迎指教!)

(上图为苹果机型下的截图)
2、通过img标签添加背景图
HTML代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="format-detection" content="email=no"/>
<title></title>
<style>
*{margin:0; padding:0;}
</style>
</head>
<body>
<div id="wrap">
<img class="imgBcground" src="images/page-small.jpg" alt="">
</div>
</body>
</html>查看页面效果时发现,图片是以百分百实际大小呈现,显然不是我们想要的效果

跟上面的例子很相像,我们只需要稍加修改就好
HTML代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="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>
<div id="wrap">
<img class="imgBcground" src="images/page-small.jpg" alt="">
</div>
</body>
</html>在不同模拟机型下查看页面效果均可以实现:

关于background-size属性,W3C是这么定义的

以上就是使用css给未知宽高的元素添加背景图片方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号