View Box
You can use the
viewBox attribute on these elements: <svg>, <marker>, <pattern>, <symbol>, <view>The viewBox attribute defines the position (x, y) and dimension (width, height) of an SVG viewport.
SVG attributes
viewBox
Defines the position and dimension of an SVG viewport.
Specify 4 numbers representing min-x, min-y, width, and height.
min-xandmin-ycan be negative.- Negative or zero of
widthorheightdisables rendering of an element.
<!-- Only see the top-left portion of the SVG -->
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
width="100"
height="100"
>
<circle cx="100" cy="100" r="50" fill="red"/>
</svg> | LIVE PREVIEW
preserveAspectRatio
Indicates how an element with a viewBox (or an <image> element) with a given aspect ratio must fit into a viewport with a different aspect ratio.
Specify none (just squeeze/stretch the content to fit the viewport), or an "alignment" and optionally a meet or slice value (this will preserve the aspect ratio).
- An "alignment" value is in the form of
x(Min|Mid|Max)Y(Min|Mid|Max):Minmeans align the top/leftMidmeans align the centerMaxmeans align the bottom/right
meet(default) means the entireviewBoxmust be contained in the viewport ("contain").slicemeans theviewBoxmust cover the entire viewport ("cover").
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<!-- insert image -->
<image x="0" y="0" width="100" height="100" href="/res/unsplash/andrew-ridley-jR4Zf-riEjI-unsplash.jpg" preserveAspectRatio="xMidYMid meet" />
<!-- rectangle border -->
<rect x="0" y="0" width="100%" height="100%" fill="none" stroke-width="5" stroke="red" />
</svg> | LIVE PREVIEW
References
- viewBox (MDN) — https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox
- preserveAspectRatio (MDN) — https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio