Setting Both the Background Color and Fill for Inline SVG using CSS
Scenario
We have created the inline SVG logo for FSAlpha. We did this but creating a square and using difference
to cut the Alpha
from the square. The end result is:
<svg class="fsalpha-Logo" version="1.1" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><path d="m0 0v200h200v-200zm88.928 37.415c22.181 0 35.375 11.34 39.583 34.02l10.591-31.345h17.545l-21.931 64.936 4.2792 23.429c0.64191 3.4947 2.2113 6.7041 4.7074 9.6283 2.9242 3.4234 5.5275 5.1348 7.8096 5.1348h9.414v16.69h-11.767c-6.7041 0-13.052-2.9957-19.043-8.9865-2.9242-2.9955-4.9924-7.6316-6.2048-13.907-3.2808 7.9166-8.2733 14.977-14.978 21.183-3.1381 2.9242-9.8067 4.3861-20.005 4.3861-16.76 0-29.205-5.4202-37.336-16.261-8.3444-11.197-12.517-26.602-12.517-46.216 0-20.968 4.529-36.374 13.587-46.216 10.056-10.983 22.145-16.475 36.267-16.475zm0 16.69c-9.5569 0-16.51 3.9228-20.861 11.768-5.4916 9.8422-8.2374 21.254-8.2374 34.234 0 15.691 2.6745 27.28 8.0235 34.769 5.4202 7.6312 12.445 11.447 21.075 11.447 9.5569 0 16.903-7.596 22.038-22.787l6.5261-19.363-4.7074-24.713c-3.2094-16.903-11.162-25.354-23.857-25.354z" fill="#4d4d4d" stroke-width="3.7795"/></svg>
We want to introduce css classes such that we can color the square and the alpha separately.
Approach
First remove fill=”#4d4d4d”
.
On the svg
element add the class:
<svg class="fsalpha-Logo--alpha" ...</svg>
On the path
element add the class:
<path class="fsalpha-Logo--square"
The final result is this:
<svg class="fsalpha-Logo--alpha" version="1.1" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><path class="fsalpha-Logo--square" d="m0 0v200h200v-200zm88.928 37.415c22.181 0 35.375 11.34 39.583 34.02l10.591-31.345h17.545l-21.931 64.936 4.2792 23.429c0.64191 3.4947 2.2113 6.7041 4.7074 9.6283 2.9242 3.4234 5.5275 5.1348 7.8096 5.1348h9.414v16.69h-11.767c-6.7041 0-13.052-2.9957-19.043-8.9865-2.9242-2.9955-4.9924-7.6316-6.2048-13.907-3.2808 7.9166-8.2733 14.977-14.978 21.183-3.1381 2.9242-9.8067 4.3861-20.005 4.3861-16.76 0-29.205-5.4202-37.336-16.261-8.3444-11.197-12.517-26.602-12.517-46.216 0-20.968 4.529-36.374 13.587-46.216 10.056-10.983 22.145-16.475 36.267-16.475zm0 16.69c-9.5569 0-16.51 3.9228-20.861 11.768-5.4916 9.8422-8.2374 21.254-8.2374 34.234 0 15.691 2.6745 27.28 8.0235 34.769 5.4202 7.6312 12.445 11.447 21.075 11.447 9.5569 0 16.903-7.596 22.038-22.787l6.5261-19.363-4.7074-24.713c-3.2094-16.903-11.162-25.354-23.857-25.354z" stroke-width="3.7795"/></svg>
CSS
We can now control both the color of the color of the alpha
and the square with CSS like this:
.fsalpha-Logo--alpha {
background-color:yellow;
width: 200px;
height: 200px;
}.fsalpha-Logo--square {
fill:gray;
}