-1

I want to display an SVG image inside a position:fixed div. I have

<div class="main">
  <svg class="svg" viewBox="0 0 180 100">
    <rect height="100%" width="100%" fill="#003300"></rect>
  </svg>
</div>

and style

.main {
  position:fixed;
  left: 100px;
  height: 100%;
  width:100%;
  background: #33AAAA;
}

.svg {
  display: block;
  height: 100%;
  width: 100%;
  position:static;
}

I want to center the SVG horizontally and vertically. I get a strange behavior. Changing the size of the browser window, shows that when the svg is smaller than available width, it is weirdly placed. For example: here there is more space on the left than on the right.

Codepen (including CSS reset): Codepen

Paolo
  • 2,461
  • 5
  • 31
  • 45
  • you have left: 100px; on main class. thats why your svg left is empty. – Alireza Jun 06 '17 at 18:24
  • That is not the point. I want to center the dark green rectangle in the light one. Maybe the left has something to do... – Paolo Jun 06 '17 at 18:27
  • The answer might be therehttps://stackoverflow.com/questions/41822510/center-an-svg-inside-a-div?rq=1 I am testing it – Paolo Jun 06 '17 at 18:27
  • Possible duplicate of [How do I center an SVG in a div?](https://stackoverflow.com/questions/8639383/how-do-i-center-an-svg-in-a-div) – Rob Jun 06 '17 at 18:43

2 Answers2

1

You are setting the width to 100%, then shifting it over by 100px. The width is still calculated as whatever the 100% width is. To center it the way you want, you will need to subtract 100px from the width or nest things differently.

.main {
  position:fixed;  
  left:100px;
  height: 100%;
  width:calc(100% - 100px);
  background: #33AAAA;
}
Tank
  • 1,006
  • 7
  • 17
0

It looks like its because you have the left: 100px in your main class. If you take that out it centers correctly.

here is the main class that should work:

.main {
  position:fixed;  
  left:100px;
  height: 100%;
  right: 0;
  top:0;
  bottom:0;
  background: #33AAAA;
}
joshsisley
  • 310
  • 2
  • 11
  • Yes but I do not want to have the light green to fill the whole viewport. I want to leave some space on the left for other things – Paolo Jun 06 '17 at 18:31
  • In that case check out my edited answer. That should work if you adjust your `main` class to that. – joshsisley Jun 06 '17 at 18:35