实现background-size: cover的几种方法

2019-05-22  本文已影响0人  丘比特爱上猫
image.png
  1. background实现
<!DOCTYPE html>
<html lang="zh-cn">
<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">
    <title>Document</title>
    <style>
        div.test{
            width: 200px;
            height: 200px;
            margin: 50px;
            float: left;
        }
        .test2{
            background: url("https://img.haomeiwen.com/i5809200/c82be83f96251f86.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240") no-repeat center/cover;
        }
    </style>
</head>
<body>
    <!-- background -->
    <div class="test2 test">
    </div>

</body>
</html>
  1. img标签实现
<!DOCTYPE html>
<html lang="zh-cn">
<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">
    <title>Document</title>
    <style>
        div.test{
            width: 200px;
            height: 200px;
            margin: 50px;
            float: left;
        }
        .test1 img{
            width: 200px;
            height: 200px;
            object-fit:cover;
        }
    </style>
</head>
<body>
    <!-- object-fit -->
    <div class="test1 test">
        <img src="https://img.haomeiwen.com/i5809200/c82be83f96251f86.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="">
    </div>
</body>
</html>
  1. svg实现
<!DOCTYPE html>
<html lang="zh-cn">
<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">
    <title>Document</title>
    <style>
        svg{
            width: 200px;
            height: 200px;
            margin: 50px;
            float: left;
        }
    </style>
</head>
<body>
    <!-- svg -->
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> 
        <image preserveAspectRatio="xMidYMid slice" x="0" y="0" width="100%" height="100%" xlink:href="https://img.haomeiwen.com/i5809200/c82be83f96251f86.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"/>
    </svg>

</body>
</html>

codepen 中自己试试吧

上一篇 下一篇

猜你喜欢

热点阅读