如果容器显示为flex,为什么SVG宽度为0?

问题描述 投票:1回答:1

当我在浏览器中运行以下代码时:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
    svg {
      border:1px solid green;
      width:200px !important;
      height:200px;
    }
    #container {
      position:fixed;
      top:300px;
      left:800px;
      width:1px;
      height:1px;
      overflow:visible;

      display:flex;
      flex-wrap:wrap;
      justify-content:center;
      align-content:center;
    }
    </style>
  </head>
  <body>
    <div id="container">
      <svg class="e3" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="50"/>
      </svg>
    </div>
  </body>
</html>

我得到的只是浏览器中的2像素垂直线。看来我的SVG的宽度是0(不包括绿色边框)。当我删除CSS规则display:flex时,我的SVG圆圈就会出现。我试图强迫我的SVG具有width: 200px !important;,但此规则似乎没有生效。

为什么我在容器上使用display:flex时,我的SVG为什么不遵守200px规则?

svg flexbox
1个回答
0
投票

我相信您的SVG节点未按预期显示,因为它的默认位置为static。如果将SVG节点更改为absolute,则将获得所需的行为。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <style>
    svg {
      position: absolute;
      border: 1px solid green;
      width: 200px;
      height: 200px;
    }
    
    #container {
      position: fixed;
      /* changed these for ease of viewing */
      top: 30px;
      left: 150px;
      width: 1px;
      height: 1px;
      overflow: visible;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      align-content: center;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <div id="container">
    <svg class="e3" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
        <circle cx="50" cy="50" r="50"/>
      </svg>
  </div>
</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.