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

标签 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>

最佳答案

使用 background-size: contain 而不是 cover 并使用 background-position: center center 使其保持居中。

DEMO

查看 documentation来自 W3schools:

Cover

Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area

Contain

Scale the image to the largest size such that both its width and its height can fit inside the content area

关于html - 如何使我的 div 的 svg 背景图像动态缩放并保持在 div 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215902/

相关文章:

css - 标题上的透明框

javascript - 什么是 Radius Manager?如何自定义它?

css - 让子 div 出现在绝对定位的父元素之上

jquery - 使多个 div 相互 float

javascript - Snap.svg 沿路径拖动组并保存位置

javascript - Array.map() 和 D3 选择?

javascript - PHP 日期验证功能

php - 在wordpress中使背景图像动态化

javascript - 将图像覆盖在 div 中心水平和中心垂直在 div 上

css - 如何使 SVG 元素上的 CSS @keyframes 动画在 Firefox 中更流畅且占用资源更少?