Why do scrollbars appear when using a SVG element

2019-05-16 23:03发布

My aim is to have a <div> with a fixed size (dynamically set through JavaScript) that is only containing an <svg> element. When this <svg> is bigger than the parent <div> scrollbars should appear. When it's smaller, it's size should be set to those of the parent <div> - but no scrollbars should appear.

This isn't working as expected as a little bit of code can show:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script type="text/javascript" src="lib/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="lib/jquery-ui-1.8.7.custom.min.js"></script>
    <script type="text/javascript" src="lib/jquery.svg.js"></script>
    <script type="text/javascript">
      $(document).ready(function() {
        $('#editor').svg();
      });
    </script>
  </head>
  <body>
    <div id="editor" style="width:500px;height:500px;overflow:auto"></div>
  </body>
</html>

This will create a nearly empty page, that contains a <div> with the fixed size of 500x500px - and a <svg width="500" height="500"> inside. This SVG has scrollbars - although they are not needed as the size would be a perfect fit.

That this will only happen with a <svg> can be easily shown when the demo is modified to

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script type="text/javascript" src="lib/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="lib/jquery-ui-1.8.7.custom.min.js"></script>
    <script type="text/javascript" src="lib/jquery.svg.js"></script>
  </head>
  <body>    
    <div style="width:500px;height:500px;overflow:auto"><div style="width:500px;height:500px"></div></div>
  </body>
</html>

So now a <div> is inside of the parent <div> of exactly the same size - and the scrollbars are appearing.

Can someone enlighten me, why the <div> and the <svg> are behaving differently?

And how I can embed an SVG inside the parent <div> without appearing scrollbars when the size is the same (and with appearing ones when the size gets bigger?)

Note: This is tested with Firefox and Chromium.

标签: jquery html svg
1条回答
时光不老,我们不散
2楼-- · 2019-05-16 23:56

The difference is because div is display: block; by default whereas svg is display: inline; so you're hitting an issue with the text baseline alignment that doesn't happen with the div. Either of the following should remove the scrollbars if added to your CSS:

svg { display:block; }

Or;

svg { vertical-align: top; }
查看更多
登录 后发表回答