我想在CSS :before
元素中显示图像。
.withimage:before {
content: url(path/to/image.svg);
display: block;
height: 20px;
width: 20px;
}
问题是,height
和width
应用于元素,但SVG不会缩小。如何将尺寸应用于之前创建的实际元素?
答案 0 :(得分:12)
您可以使用svg作为背景图像:
.withimage:before {
content: "";
display:block;
height:125px;
width:125px;
background-size: 125px 125px;
background-image: url(test.svg);
background-repeat: no-repeat;
}
这是example
你也可以尝试使用这个:
.withimage:before {
content: url("data:image/svg+xml; utf8, <svg.. code here</svg>");
display:block;
height:20px;
width:20px;
}
答案 1 :(得分:1)
比例转换对我有用:
::before {
content: url(path/to/image.svg); // source image is 24px wide
transform: scale(0.5); // will be rendered 12px wide
}
答案 2 :(得分:0)
大多数浏览器不支持img标记上的:after
,:before
,但您可以创建一个高度和宽度为div
并为其指定background
/* Styles go here */
.withimage:before {
content:"";
background: url(test.svg);
background-size: cover;
display: block;
width:20px;
height: 10px;
}
.withimage{
background: pink;
height: 100px;
width: 100px;
}
答案 3 :(得分:0)
出于某些原因,有时我们不想使用背景图片。我遇到了同样的问题,无论SVG的宽度和高度如何,它都不会生效。原因是SVG缺少viewBox。
我刚刚在内容中添加了viewBox ='0 0 16 16'和violá!