我有一个问题:svg 栏没有响应(见图),有人可能有解决方案吗?我现在认真地搜索了大约 1 1/2 小时,我真的很沮丧:/
这是我的代码:
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>
最佳答案
您面临的问题实际上有两个方面:
- 您在标记中声明了 SVG 元素的显式宽度和高度(例如
width="345" height="15"
)。这会强制保持纵横比。 - 你没有申报
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/