Hudson Taylor
Hudson Taylor

Reputation: 1162

Odd margins on SVG Element

I have a simple SVG element with height and width equal to 80%. I am also applying a margin of 10% to the element to center the SVG on the page. However, for some odd reason, the margin seems to be creating a y-overflow so that the page is scrollable. This doesn't make much sense as I am applying styles that should add up to no more than 100% vertically and horizontally. Here's my code:

html, body {height: 100%;}

* {
  margin: 0;
  padding: 0;
}

svg {
  margin: 10%;
  height: 80%;
  width: 80%;
  background: #ddd;
}

svg path {
  fill: none;
  stroke: #000;
  stroke-linejoin: round;
  transition: 0.2s;
}
<svg viewBox="0 0 40 40">
  <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" />
</svg>

Essentially, I want the SVG to be centered with percent margins, and I don't want the body to be scrollable.

Thanks in advance!

Upvotes: 0

Views: 6448

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101820

Check the definition of margin. Percentage margins are calculated relative to the width of the containing block.

So you are setting the top and bottom margins too large. Hence the scrolling.

Solution

Vertically centering an element of unknown size is quite tricky. CSS does not make it easy. But there is a little trick you can use as explained here.

The idea is to use a second element that is 100% height, then vertically center both elements, so that the smaller one (the SVG in our case) becomes centred.

html, body {height: 100%;}

* {
  margin: 0;
  padding: 0;
}

svg {
  height: 80%;
  width: 80%;
  background: #ddd;
  vertical-align: middle;
}

svg path {
  fill: none;
  stroke: #000;
  stroke-linejoin: round;
  transition: 0.2s;
}

.wrapper:before {
  content: '\200B'; /* zero width space */
  display: inline-block;
  height: 100%; 
  vertical-align: middle;
}

.wrapper {
  text-align: center;
  height: 100%;
}
<div class="wrapper">

  <svg viewBox="0 0 40 40">
    <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" />
  </svg>

</div>

Upvotes: 1

Santosh
Santosh

Reputation: 1839

Add overflow-y:hidden to body to prevent it from scrolling. Here is the code snippet below.

html,
body {
  height: 100%;
}

body {
  overflow-y: hidden;
}

* {
  margin: 0;
  padding: 0;
}

svg {
  margin: 10%;
  height: 80%;
  width: 80%;
  background: #ddd;
  top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    position:absolute;
}

svg path {
  fill: none;
  stroke: #000;
  stroke-linejoin: round;
  transition: 0.2s;
}
<svg viewBox="0 0 40 40">
  <path d="M15,5 l10,0 l0,10 l10,0 l0,10 l-10,0 l0,10 l-10,0 l0,-10 l-10,0 l0,-10 l10,0 l0,-10 Z" />
</svg>

Upvotes: 0

Related Questions