html如何使得背景图片能够按浏览器窗口大小比例显示

html如何使得背景图片能够按浏览器窗口大小比例显示,而不会出现拉伸图片的情况,例如

img

img

设置
background-size: cover;
或者
background-size: contain;
cover: 将背景图像等比缩放到完全覆盖容器,背景图像有可能超出容器。
contain: 将背景图像等比缩放到宽度或高度与容器的宽度或高度相等,背景图像始终被包含在容器内。

img

img

你题目的解答代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title> 页面名称 </title>
<style>
    .p1 {
        width: 600px;
        height: 300px;
        background: url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-10-28%2F5f99180e8dd5a.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655476992&t=b8c489e8bf0035b98c4842af7fc555c6) no-repeat center center;
        background-size: cover;
        border: 5px solid #999;
    }
    .p2 {
        width: 300px;
        height: 400px;
        background: url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-10-28%2F5f99180e8dd5a.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655476992&t=b8c489e8bf0035b98c4842af7fc555c6) no-repeat center center;
        background-size: cover;
        border: 5px solid #999;
    }
    .p3 {
        width: 600px;
        height: 300px;
        background: url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-10-28%2F5f99180e8dd5a.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655476992&t=b8c489e8bf0035b98c4842af7fc555c6) no-repeat center center;
         background-size: contain;
        border: 5px solid #999;
    }
    .p4 {
        width: 300px;
        height: 400px;
        background: url(https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2020-10-28%2F5f99180e8dd5a.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1655476992&t=b8c489e8bf0035b98c4842af7fc555c6) no-repeat center center;
         background-size: contain;
        border: 5px solid #999;
    }
</style>
</head>
<body>
    
    cover:容器高度不够.将背景图像等比缩放到完全覆盖容器,背景图像上下可能超出容器。
    <div class="p1"></div>
    cover:容器宽度不够.将背景图像等比缩放到完全覆盖容器,背景图像左右可能超出容器。
    <div class="p2"></div>
    contain: 将背景图像等比缩放到宽度或高度与容器的宽度或高度相等,背景图像始终被包含在容器内
    <div class="p3"></div>
    <div class="p4"></div>

</body>
</html>

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632