如何创建响应式的嵌套SVG线以相对于其他元素?

3
我有一个嵌套的SVG,其中包含3个元素。两个三角形位于左右两侧,中间是一条直线。我想要获得响应式的直线(直线应该只有两个三角形之间可用的宽度),无论在水平还是垂直方向上都是如此。我尝试设置百分比的宽度,但仅在水平缩放时起作用。当我在垂直方向上进行调整大小时,它无法正常工作,因为三角形的宽度会改变。这里是一个Codepen链接:https://codepen.io/roppazvan/pen/dyyPKKL?editors=1100
    <svg
        class='input-source'
        stroke='black'
        stroke-width='0'
        fill="black">
        <rect  x="20" y="20%" width="100%" height="60%" 
            stroke='black'
            stroke-width='0'
        >
        </rect>
              <!-- The right head --> 
        <svg class='head input-source' id='right' 
            height="100%"
            width='100%' 
            viewBox="0 0 20 40"
            preserveAspectRatio="xMaxYMid"
            >
            <rect width="100%" height="100%"/>
        </svg>

        <!-- The left head --> 
        <svg class='head input-source' id='left' 
            height="100%"
            width='100%' 
            viewBox="0 0 15 30"
            preserveAspectRatio="xMinYMid"
            >
            <rect width="100%" height="100%"/>
        </svg>
    </svg>   
</svg>


<svg width="110px" height="40px" version="1.0" state='normal'>
    <svg
        class='input-source'
        stroke='black'
        stroke-width='0'
        fill="black">
        <rect  x="20" y="20%" width="100%" height="60%" 
            stroke='black'
            stroke-width='0'
        >
        </rect>
              <!-- The right head --> 
        <svg class='head input-source' id='right' 
            height="100%"
            width='100%' 
            viewBox="0 0 20 40"
            preserveAspectRatio="xMaxYMid"
            >
            <rect width="100%" height="100%"/>
        </svg>

        <!-- The left head --> 
        <svg class='head input-source' id='left' 
            height="100%"
            width='100%' 
            viewBox="0 0 15 30"
            preserveAspectRatio="xMinYMid"
            >
            <rect width="100%" height="100%"/>
        </svg>
    </svg>   
</svg>

1个回答

2

最简单、最易于实现和理解的方法可能就是使用flex-box。

#svg-container {
  margin-top: 100px;
  width: 100%;
  border: 1px solid #bada55;

  display: flex;
  flex-direction: row;
}

svg {
  height: 10vh;
}

/* stretch the middle box */
svg:nth-child(2) {
  flex: 1;
}
<div id="svg-container">
<!--    left head  -->
  <svg viewBox="0 0 14 14" preserveAspectRatio="xMinYMid" opacity="0.5">
     <polygon points="0,7 14,0 14,14 " />
  </svg>
<!--     line -->
  <svg viewBox="0 0 14 14" preserveAspectRatio="none">
    <rect y="30%" width="100%" height="40%" />
  </svg>
<!--     right head -->
  <svg viewBox="0 0 14 14" preserveAspectRatio="xMaxYMid" opacity="0.5">
    <polygon points="14,7 0,0 0,14 "/>
  </svg>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接