1

Can someone please explain the unexpected behavior for margin:0 style in body

Here's my code snippet:

<!DOCTYPE html>
    <html>
    <head>
     <title>SVG Shapes</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <style>
     body, html {
      padding: 10px;
      margin: 0;
     }
     svg {
      width: 100%;
      height: 100%;
      padding: 15px;
      border: 1px solid red;
     }
     </style>
    </head>
    <body>
     <svg>
      <rect width=300 height="100" style="fill:rgb(0, 0, 255); stroke-width:3; stroke:rgb(0,0,0);" />
     </svg>
    </body>
    </html>

What I'm expecting is that the svg will be inside the body(with a padding of 10px on all sides) and there won't be any scroll bar. But what is happening is that top and left padding for body is working fine, but the right padding is not. The right border for svg is sticking with the body(check out the image for clarification).

mmk
  • 480
  • 3
  • 10
amit_vickey
  • 45
  • 1
  • 9

3 Answers3

2

The width: 100% is the actual width of the parent element, which in your case is the body element.

When you add a padding to it, you'll get a width of 100% + padding. you can add box-sizing: border-box; to the svg style so the browser will calculate the width including the padding.

 body, html {
        padding: 10px;
        margin: 0;
    }
    svg {
        width: 100%;
        height: 100%;
        padding: 15px;
        border: 1px solid red;
        box-sizing: border-box; 
    }
<svg>
   <rect width=300 height="100" style="fill:rgb(0, 0, 255); stroke-width:3; stroke:rgb(0,0,0);" />
</svg>
Itay Gal
  • 10,706
  • 6
  • 36
  • 75
1

Use box-sizing: border-box.

By default, all elements have box-sizing: content-box set. In this setting, browser only counts the width and height of the actual content in elements.

In box-sizing: border-box, browser includes everything within the border in its calculation of elements.

<!DOCTYPE html>
<html>
<head>
    <title>SVG Shapes</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    * {
      box-sizing: border-box;
    }
    body, html {
        padding: 10px;
        margin: 0;
    }
    svg {
        width: 100%;
        height: 100%;
        padding: 15px;
        border: 1px solid red;
    }
    </style>
</head>
<body>
    <svg>
        <rect width=300 height="100" style="fill:rgb(0, 0, 255); stroke-width:3; stroke:rgb(0,0,0);" />
    </svg>
</body>
</html>
yqlim
  • 6,898
  • 3
  • 19
  • 43
0

No need to change in HTML file. Only Add below CSS property in svg class.

 svg {
     box-sizing: border-box;
 }