4

需求描述

页面中有一个图片,页面宽度变小(比如打开控制台,拖动边栏),图片宽高,要随之等比例自适应缩放,如下效果图

效果图

实现方案

  • 方案一:使用宽度百分比和vw
  • 方案二:宽度百分比加高度被padding-top撑开
  • 方案三:搭配伪元素

直接上代码,复制粘贴即可使用

方案一:使用宽度百分比和vw

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .adapt {
            width: 36%;
            height: 36vw;
            background-color: pink;
        }

        img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <div class="adapt">
        <img src="http://ashuai.work/static/img/avantar.png">
    </div>
</body>

</html>

方案二:宽度百分比加高度被padding-top撑开

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .adapt {
            width: 36%;
            height: 0;
            padding-top: 36%;
            background: pink;
            position: relative;
        }

        img {
            width: 100%;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="adapt">
        <img src="http://ashuai.work/static/img/avantar.png">
    </div>
</body>

</html>

方案三:搭配伪元素

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .adapt {
            width: 36%;
            overflow: hidden;
            background: pink;
            position: relative;
        }

        .adapt::after {
            content: '';
            display: block;
            margin-top: 100%;
        }

        img {
            width: 100%;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="adapt">
        <img src="http://ashuai.work/static/img/avantar.png">
    </div>
</body>

</html>
A good memory is better than a bad pen. Write it down...

水冗水孚
1.1k 声望584 粉丝

每一个不曾起舞的日子,都是对生命的辜负