How do I center an SVG in a div?

后端 未结 12 1642
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 10:11

I have an SVG that I am trying to center in a div. The div has a width or 900px. The SVG has a width of 400px. The SVG has its margin-left and margin-right set to auto. Does

相关标签:
12条回答
  • 2020-11-27 10:54

    Above answers did not work for me. Adding the attribute preserveAspectRatio="xMidYMin" to the <svg> tag did the trick though. The viewBox attribute needs to be specified for this to work as well. Source: Mozilla developer network

    0 讨论(0)
  • 2020-11-27 10:58

    I had to use

    display: inline-block;
    
    0 讨论(0)
  • 2020-11-27 11:03

    Flexbox is another approach: add

    .container {
      display: flex;
      justify-content: center;
    }

    And add the .container class to the div which contains your svg.

    0 讨论(0)
  • 2020-11-27 11:03

    Put this two lines in style.css In your specified div class.

       display: block;
       margin: auto;
    

    and then try to run it, you will be able to see that .svg aligned in the center.

    0 讨论(0)
  • 2020-11-27 11:08

    For me, the fix was to add margin: 0 auto; onto the element containing the <svg>.

    Like this:

    <div style="margin: 0 auto">
       <svg ...</svg>
    </div>
    
    0 讨论(0)
  • 2020-11-27 11:11

    Answers above look incomplete as they are talking from css point of view only.

    positioning of svg within viewport is affected by two svg attributes

    1. viewBox: defines the rectangle area for svg to cover.
    2. preserveAspectRatio: defined where to place the viewBox wrt viewport and how to strech it if viewport changes.

    Follow this link from codepen for detailed description

    <svg viewBox="70 160 800 190" preserveAspectRatio="xMaxYMax meet">
    
    0 讨论(0)
提交回复
热议问题