Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS padding property for svg elements

I can't figure out how the CSS padding property is interpreted for svg elements. The following snippet (jsFiddle):

<!DOCTYPE html>
<meta charset="utf-8">
<title>noob d3</title>

<style>
svg{background-color:beige;
    padding:0px 0px 50px 50px;}
rect{fill:red;
     stroke:none;
     shape-rendering:crispEdges;}
</style>

<body>
  <script src="//d3js.org/d3.v3.min.js"></script>
  <script>
d3.select("body")
.append("svg")
  .attr("width", 155)
  .attr("height", 105)
.append("g")
.append("rect")
  .attr("class", "frame")
  .attr("x", 50)
  .attr("y", 50)
  .attr("width", 50)
  .attr("height", 50);
  </script>
</body>

... displays significantly differently in Firefox and Chrome. What's worse, neither display really makes sense to me: the size of the displayed svg element (the "beige" rectangle) looks to be significantly bigger than what I expected.

So my question is two-fold: 1) How is the padding property of an svg element supposed to affect where things get drawn within it? 2) Is there a polyfill that will ensure that both Chrome and Firefox both handle padding in the same way?

like image 469
kjo Avatar asked Oct 30 '13 22:10

kjo


People also ask

Can you add padding to SVG?

Padding on an svg element actually widens the canvas upon which svg shapes can be visible. For instance, if you have an element that is on the edge of an SVG canvas, then you can add padding that will make that shape not cut off. Whereas margin will just affect the right/left positioning of the svg element.

Can CSS be applied to SVGs?

There are many Scalable Vector Graphics (SVG), but only certain attributes can be applied as CSS to SVG. Presentation attributes are used to style SVG elements and can be used as CSS properties. Some of these attributes are SVG-only while others are already shared in CSS, such as font-size or opacity .

How do you add padding to an image in CSS?

The CSS padding properties are used to generate space around an element's content, inside of any defined borders. With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).

How do I get rid of SVG padding?

This is done using the attribute "preserveAspectRatio" and setting it to "none". Hopefully this helps some of your understanding of SVGs, as they're a really useful tool!


1 Answers

AFAIK, the SVG standard doesn't specify anything like padding, which is why it's handled inconsistently. Just set the SVG to the size you want (with padding) and maybe add a rect to make it appear like you want it to appear.

like image 85
Lars Kotthoff Avatar answered Oct 13 '22 00:10

Lars Kotthoff