Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set size of SVG image in :before pseudo-class?

Tags:

I want to display an image in a CSS :before element.

.withimage:before {   content: url(path/to/image.svg);   display: block;   height: 20px;   width: 20px; } 

The problem is, the height and width are applied to the element, but the SVG doesn't scale down. How do I apply the sizes to the actual element created by before?

Plnkr example: https://plnkr.co/edit/UgryaObojs6PCU579oGY

like image 218
Jorn Avatar asked Mar 28 '16 09:03

Jorn


People also ask

How do you use SVG as content in pseudo element before or after?

SVG content can be added using these pseudo-elements by following the methods described below: Method 1: Using the background-image property: The background-image property is used to set one or more background images to an element.

How do I control SVG size?

Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.

Does SVGs have default size?

The thing is: SVG images don't have a "size" in the sense you are probably thinking of. On the other hand, they DO have a height-to-width ratio. This ratio can usually be found in the viewBox attribute.


Video Answer


2 Answers

You can use svg as background-image:

.withimage:before {   content: "";   display:block;   height:125px;   width:125px;   background-size: 125px 125px;   background-image: url(test.svg);   background-repeat: no-repeat; } 

Here is example

Also you can try use this one:

.withimage:before {   content: url("data:image/svg+xml; utf8, <svg.. code here</svg>");     display:block;     height:20px;     width:20px; } 
like image 103
oboshto Avatar answered Sep 21 '22 18:09

oboshto


Scale transform worked for me:

::before {     content: url(path/to/image.svg); // source image is 24px wide     transform: scale(0.5);           // will be rendered 12px wide   } 
like image 44
Martin Avatar answered Sep 19 '22 18:09

Martin