Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position SVG to the left when embedded via img

Tags:

html

css

image

svg

I'm embedding a SVG with a width of 100% and automatic height. The maximum height is 80% of the viewport.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test</title>
    <style>
        html, body{
            width: 100%;
            height: 100%;   
        }
        img{
            width: 100%;
            height: auto;
            max-height: 80vh;
        }
    </style>
</head>
<body>
    <img src="example.svg">
</body>
</html>

If the SVG doesn't fit into the 80% of the viewport it'll be cropped by the specified maximum height. The problem is that this also centeres the SVG:

centerd red area

What I need is to keep the embedding via <img> as this is what I receive from a CMS and position the SVG to the left like a background-position: left top; would do. How to position the <img> contents to the left, even if the image is cropped?

like image 942
dude Avatar asked Feb 10 '17 12:02

dude


Video Answer


1 Answers

Try to add preserveAspectRatio="xMinYMin meet" to root svg element of your svg file, like this.

<svg width="200px" height="200px" 
  viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg" 
  preserveAspectRatio="xMinYMin meet">
  <rect width="100%" height="100%" fill="red"/>
</svg>
like image 179
defghi1977 Avatar answered Sep 28 '22 06:09

defghi1977