I am working on a website where I have an SVG that covers a div. If I set this SVG as a background-image
and then apply background-position: center center
, it works as intended. On smaller screen sizes, it zooms in to its center. However, my problem is that I can't apply any additional CSS in this way.
It's possible to get the same effect what background-position: center center
does, but without background-image
. I was trying the object-fit:cover; object-position:center center
but it's not worked.
This works well
<div
style="background-image: {{asset('assets/vectors/bg.svg')}}; height: 100vh; background-position:center center"
>
But I want it to work in this way, achieving exactly the same effect.
<div>
<svg> /* So I can apply additional css on it */
</div
To achieve this behavior you have to set the SVG attribute preserveAspectRatio
to the value xMidYMid slice
like follows:
<svg viewBox="0 0 300 300" preserveAspectRatio="xMidYMid slice">
<!-- your code here -->
</svg>
The part xMidYMid
of this value means that your SVG will be placed in the middle by X
and Y
coordinations from view box.
The part slice
of this value means that your SVG will be sliced if it not fits the same position and size like its view box.
Read more about this attribute in this tutorial: Understanding SVG Coordinate Systems and Transformations