svg - 如果容器为 display flex,为什么 SVG 宽度为 0?

标签 svg flexbox

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

<!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 节点没有像您预期的那样显示,因为它的默认位置是 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>

关于svg - 如果容器为 display flex,为什么 SVG 宽度为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792503/

相关文章:

javascript - 在 IE11 中使用 CSS 动画化 SVG 路径

javascript - 在 Canvas 元素中使用 SVG evenodd 填充规则

javascript - 如何填充动态创建的 SVG(检查 DOM 是否更新)

html - 如何使用 flex 在响应式布局中调整图像大小

css - 如何在不使用媒体查询的情况下将 div 定位为较低的分辨率

javascript - Fabricjs svg解析错误

html - 第 75 行第 16 列错误 : AttValue: "or ' expected

css - 强制 flex 元素不在横轴方向增长

html - 如何放置 <aside> 元素 'aside' 主要内容

html - CSS div等高基于最小高度div