首页 > 解决方案 > 如何创建相对于其他元素的响应式嵌套 SVG 线?

问题描述

我有一个包含 3 个元素的嵌套 SVG。2 个三角形位于左右两侧,一条线位于中间。在水平和垂直调整大小时,我想获得一条响应线(线应该只有三角形之间可用的宽度)。我尝试以百分比设置宽度,但仅在水平调整大小时才有效。当我垂直调整大小时,它不起作用,因为三角形的宽度发生了变化。这是一个 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>

标签: htmlcsssvg

解决方案


实现和理解的最简单和最容易的方法可能就是使用 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>


推荐阅读