css3中background-repeat:space/round属性详解

文章2019-08-071,208 人已阅来源:网络

css3中background-repeat新增 space和round属性值,它弥补了之前css2 中无休止贴瓷砖模式的重复平铺,超出就裁剪,让背景图的控制尽量做到完美。

先看一下栗子

运行代码
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name=Copyright content=Tencent>
    <meta http-equiv=X-UA-Compatible content="IE=Edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>css3中background-repeat:space/round属性-www.tonjay.com</title>
</head>
<style>
    *{font-family: -apple-system, SF UI Text, PingFang SC, Arial, Hiragino Sans GB, Microsoft YaHei, WenQuanYi Micro Hei, sans-serif;}
    body{ background: #eee; text-align: center;}
    h2:nth-of-type(2){ margin-top: 40px;}
    .tonjay1,.tonjay2{ margin:0 auto; display: flex; justify-content: center; }
    .tonjay1 div,.tonjay2 div{ background-color: #fff; border: 1px solid #eee; display:flex; flex-wrap: wrap; align-items: center; justify-content: center; width: 200px; height: 200px; margin: 0 20px; border-radius: 3px;}
    .space{ background-repeat: space;}
    .round{ background-repeat: round;}
    p{width: 100%;}
    .tonjay1 div{background-image: url("data:image/svg+xml, %3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='60' viewBox='0 0 60 60'%3E%3Ccircle cx='30' cy='30' r='30' fill='%23eb1414'/%3E%3C/svg%3E");}
    .tonjay1 div.round2{background-image: url("data:image/svg+xml, %3Csvg xmlns='http://www.w3.org/2000/svg' width='42' height='42' viewBox='0 0 42 42'%3E%3Ccircle cx='21' cy='21' r='21' fill='%23eb1414'/%3E%3C/svg%3E");}
    .tonjay2 div{height: 100px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='background:%23000;' width='240' height='240' viewBox='0 0 240 240'%3E%3Cpath d='M240,240H0V0H240V240ZM120,48.718A71.282,71.282,0,1,0,191.282,120,71.362,71.362,0,0,0,120,48.718Z' fill='%2300a7f2'/%3E%3C/svg%3E");}
    div>div:hover{ background: #fff!important; cursor: default}
</style>
<body>
    <h2>当图片小于容器空间时</h2>
    <div class="tonjay1">
        <div class="space">space <p>img(60*60)</p></div>
        <div class="round">round(img(60*60))<p>round的第一种情况</p></div>
        <div class="round round2">round (img(42*42))<p>round的第二种情况</p></div>
    </div>
    <h2>当图片大于容器空间时</h2>
    <div class="tonjay2">
        <div class="space">space(img(240*240))</div>
        <div class="round">round(img(240*240))</div>
    </div>
</body>
</html>

当图片小于容器空间时

  • space:在不缩放的前提下尽可能多的重复图片
  • round:充分利用容器空间,重复n次之后(x/y轴方向)如果剩余空间大于等于imgWidth*50%则重复第n+1次,否则拉伸已经重复的背景图

当图片大于容器空间时

  • space:背景图不会产生缩放,会被裁切
  • round:缩放背景图至容器大小(非等比例缩放)