【问题标题】:What's the best way to center an SVG horizontally and vertically inside a div tag?在 div 标签内水平和垂直居中 SVG 的最佳方法是什么?
【发布时间】:2017-10-19 19:04:04
【问题描述】:

在 div 标签内将 SVG 水平和垂直居中的最佳方法是什么?

我知道有些方法比其他方法更好,但为此,最好的方法是什么?

    <div style="width: 64px;height: 64px;background-color: rgba(0,0,0,.7);background-repeat: no-repeat;background-size: 24px;background-position: 58% 50%;border-radius: 500px;border: 1px solid blue;cursor: pointer;">
        
        <svg viewBox="-22 0 1229 1481" width="24" height="29" style="display:block;margin: 0 auto;background-color:green;">
        <path d="M0 1394V87C0 46.3 13.3 19.8 40 7.5 66.7-4.8 98.7.3 136 23l1034 634c37.3 22.7 56 50.3 56 83s-18.7 60.3-56 83L136 1458c-37.3 22.7-69.3 27.8-96 15.5-26.7-12.3-40-38.8-40-79.5z" fill="red"/>
        </svg>
        </div>

【问题讨论】:

    标签: html svg centering


    【解决方案1】:

    如果您打算自己设置固定位置、像素大小和边距,只需调整 svg 垂直边距。

        <div style="width: 64px;height: 64px;background-color: rgba(0,0,0,.7);background-repeat: no-repeat;background-size: 24px;background-position: 58% 50%;border-radius: 500px;border: 1px solid blue;cursor: pointer;">
            
            <svg viewBox="-22 0 1229 1481" width="24" height="29" style="display:block;margin:16px auto;background-color:green;">
            <path d="M0 1394V87C0 46.3 13.3 19.8 40 7.5 66.7-4.8 98.7.3 136 23l1034 634c37.3 22.7 56 50.3 56 83s-18.7 60.3-56 83L136 1458c-37.3 22.7-69.3 27.8-96 15.5-26.7-12.3-40-38.8-40-79.5z" fill="red"/>
            </svg>
            </div>

    【讨论】:

      【解决方案2】:

      为您的 SVG 元素使用这种 css 样式

      margin: 0 auto;
      display: block;
      

      还有这个用于 DIV 元素的 css

      display: flex;
      align-items: center;
      height: 100%;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-23
        • 2012-03-28
        • 2015-08-29
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 2010-11-20
        • 2023-02-13
        相关资源
        最近更新 更多