如何使我的div的svg背景图像动态缩放并保持在div的中心

时间:2015-12-11 04:00:24

标签: html css svg

我目前正致力于以下网站设计:

enter image description here

我有两个部分(顶部和底部),它们分为两个部分(图标和内容)。我试图在图标部分使用居中的svg图像,尽管只要观看区域/浏览器窗口的大小发生变化,图像就会被切断。我怎样才能防止这种情况发生?

以下是我目前正在使用的内容:

示例 - js fiddle link

SVG图片 - svg image

HTML -

<div id="main1">
   <div id="icon1">&#160;</div>​ 
   <div id="links1">
      <p>Content</p>
      <p>Content</p>
      <p>Content</p>
   </div>
</div>
<br/>
<div id="main2">
   <div id="icon2">​​​</div>
   <div id="links2">
      <p>Content</p>
      <p>Content</p>
      <p>Content</p>
   </div>
</div>
<div class="ms-rtestate-read ms-rte-wpbox" contenteditable="false">
   <div class="ms-rtestate-notify  ms-rtestate-read a64b9522-0ca6-4ff7-a9fc-67a7a27d3071" id="div_a64b9522-0ca6-4ff7-a9fc-67a7a27d3071" unselectable="on">
   </div>
   <div id="vid_a64b9522-0ca6-4ff7-a9fc-67a7a27d3071" unselectable="on" style="display: none;">
   </div>
</div>

CSS -

<style>
#main1 > div { min-height: 100px; }
#main1 {
    /* overflow to handle inner floating block */
    overflow: hidden;
    border-radius: 25px;
    border: 2px solid #73AD21;
    padding: 20px; 
    margin-right: 5%;
    margin-left: 5%;
}

#icon1 {
    float: left;
    width: 29%;
    border-right:thin solid red;
}

#links1 {
    float: right;
    width: 70%;
}
#main2 > div { min-height: 100px; }
#main2 {
    /* overflow to handle inner floating block */
    overflow: hidden;
    border-radius: 25px;
    border: 2px solid #73AD21;
    padding: 20px; 
    margin-right: 5%;
    margin-left: 5%;
}

#icon2 {
    float: left;
    width: 29%;
    border-right:thin solid red;
    /* background: url('/support/Shared%20Documents/065__calendar.svg') no-repeat center; */
    background-image: url('/support/Shared%20Documents/065__calendar_crop.svg');
    background-repeat: no-repeat;
    background-size: cover;
}

#links2 {
    float: right;
    width: 70%;
}
</style>

1 个答案:

答案 0 :(得分:1)

使用background-size: contain代替cover并使用background-position: center center使其保持居中。

<强> DEMO

查看W3schools的documentation

  

<强>盖

     

将背景图像缩放到尽可能大,以使背景区域完全被背景图像覆盖。 背景图片的某些部分可能无法在背景定位区域中查看

     

<强>内含

     

将图像缩放到最大尺寸,使其宽度和高度都适合内容区域