html - 背景封面无法正常工作

标签 html css

我有一个问题:svg 栏没有响应(见图),有人可能有解决方案吗?我现在认真地搜索了大约 1 1/2 小时,我真的很沮丧:/

enter image description here

这是我的代码:

HTML :

<div class="overview-footer">
  <img src="assets/layout/images/dashboard/progress_day.svg" 
       style="display:inline-block;vertical-align:top;" />
  <img src="assets/layout/images/dashboard/progress_week.svg" 
       style="display:inline-block;vertical-align:top;" />
  <img src="assets/layout/images/dashboard/progress_month.svg" 
       style="display:inline-block;vertical-align:top;" />
  <div class="year"></div>
</div>

CSS :

.year {
background-image: url(assets/layout/images/dashboard/progress_year.svg);
width:100%;
height:20px;
display: table;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;

那是相关的 svg 数据:

   <rect id="Rectangle-4" fill="#D8D8D8" x="0" y="0" width="100%" height="20"></rect>
   <rect id="Rectangle-4" fill="green" x="0" y="0" width="50%" height="20"></rect>

编辑: https://plnkr.co/edit/ute15PscCtevJECeRLiE?p=preview 给你

最佳答案

您面临的问题实际上有两个方面:

  1. 您在标记中声明了 SVG 元素的显式宽度和高度(例如 width="345" height="15" )。这会强制保持纵横比。
  2. 你没有申报preserveAspectRatio="none"在您的 SVG 元素中,这意味着它们将始终按比例缩放。

问题仅在您的 <div> 时出现元素的宽度小于 345px ,这将导致浏览器以您不希望的方式缩放图像。

如果删除这两个属性,问题就会消失:https://plnkr.co/edit/g26kjqYdtf8eNQtwI2Nb?p=preview

更好的解决方案:CSS + HTML-only 解决方案

另一种解决方案是简单地使用绝对定位的伪元素来完成这项工作。您将从维护这些仅用于单一目的的 SVG 中节省大量时间,而且它们的标记也显得非常臃肿。

如果您查看下面的代码片段,对您的标记进行小幅修改和对您的 CSS 进行大修将意味着您不再需要依赖 SVG:

.overview {
  background-color: #D8D8D8;
  position: relative;
  width: 100%;
  height: 20px;
}

.overviewDay::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  background-color: orange;
  width: 80%;
}

.overviewWeek::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  background-color: blue;
  width: 25%;
}

.overviewMonth::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  background-color: red;
  width: 55%;
}

.overviewYear::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  background-color: green;
  width: 50%;
}
<div class="overview-footer">
  <div class="overview overviewDay"></div>
  <div class="overview overviewWeek"></div>
  <div class="overview overviewMonth"></div>
  <div class="overview overviewYear"></div>
</div>

关于html - 背景封面无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45503175/

相关文章:

javascript - Bootstrap - float div的固定顶部div不起作用

html - 将父 div 与子 div 一起移动?

html - 如何选择具有特定类的最后一个元素,而不是父元素中的最后一个子元素?

javascript - 如何删除 h1 标签的一部分并在其他地方使用它而不影响 h1

html - div 使用 z-index 覆盖 youtube 视频?

javascript - 有没有办法在现代浏览器(如 Chrome 42)中编写禁用保存密码的方法?

html - 在 HTML 5 中单击图像时添加声音

html - 如何使用 3 种不同的设置更改平板电脑、移动设备和更广泛设备的引导轮播?

css - 选择 HTML 元素中的特定文本

jquery - 如何获取 jqm rangeslider 和 sliderthumb 之间的标签?