代码之家  ›  专栏  ›  技术社区  ›  blub

具有百分比和像素值的响应SVG

svg
  •  0
  • blub  · 技术社区  · 7 年前

    我可以创建一个SVG,在任何给定的百分比“0%-100%”,这样在calc的帮助下,圆角边框(以像素为单位)就不会包含在“百分比宽度”中。 calc(100% - 25px)

    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="50">
    <rect fill="lightblue" y="0" x="0" width="100%" height="50" rx="25" ry="25"></rect>
    <g class="percentage">
        <line class="100pct" x1="calc(100% - 25px)" x2="calc(100% - 25px)" y1="0" y2="50" stroke="red" stroke-width="4"></line>
    </g>
    </svg>

    但问题是,是否可以在不计算旧浏览器的情况下创建相同的SVG?

    我可以使用转换和转换来考虑一个圆角,但我不知道如何限制宽度/添加某种边距。

    百分比变化,所以一个共享的翻译只会让我走到一半,这里红色的100%行超出了界限:

    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="50">
    <rect fill="lightblue" y="0" x="0" width="100%" height="50" rx="25" ry="25"></rect>
    <g class="percentage" transform="translate(25, 0)">
        <line class="0pct" x1="0%" x2="0%" y1="0" y2="50"  stroke="blue" stroke-width="4"></line>
        <line class="100pct" x1="100%" x2="100%" y1="0" y2="50" stroke="red" stroke-width="4"></line>
    </g>
    </svg>
    1 回复  |  直到 7 年前
        1
  •  2
  •   ccprog    7 年前

    是否确实有任何浏览器支持上述语法?如果是,它甚至违反了 SVG2 spec :

    未来的规范可能会将__x1_、__y1_、_x2_和_y2_秷属性转换为几何属性。目前,它们只能通过元素属性指定,而不能通过CSS指定。

    (及之后) calc() 是一个css函数,它只能在css上下文中使用。)

    在所有支持SVG的浏览器中工作的是将x/y值与转换相结合;unitless=px值转到transform属性,单位(百分比)转到x/y属性。

    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="50">
        <rect fill="lightblue" y="0" x="0" width="100%" height="50" rx="25" ry="25"></rect>
        <g class="percentage" >
            <line class="0pct" x1="100%" x2="100%" y1="0" y2="50" transform="translate(-25, 0)" stroke="red" stroke-width="4"></line>
        </g>
    </svg>

    除了SVG 1.1 transform 属性,还有CSS 转型 属性及其2d函数的实现相当公平(例外:ie和edge<17)。他们 必须 使用单位标识符,以及 应该 还支持嵌套 () 功能。我没有该组合的兼容性数据,但在 caniuse.com .

    当前不起作用的是将CSS转换语法用作表示属性( CSS transform spec 尚未在这方面实现),因此您需要在 style 属性。

    <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="50">
        <rect fill="lightblue" y="0" x="0" width="100%" height="50" rx="25" ry="25"></rect>
        <g class="percentage" stroke="red" stroke-width="4" >
            <line class="0pct" x1="0" x2="0" y1="0" y2="50"
                  style="transform:translate(calc(0 * (100% - 50px) + 25px))" />
            <line class="50pct" x1="0" x2="0" y1="0" y2="50"
                  style="transform:translate(calc(0.5 * (100% - 50px) + 25px))" />
            <line class="100pct" x1="0" x2="0" y1="0" y2="50"
                  style="transform:translate(calc(1 * (100% - 50px) + 25px))" />
        </g>
    </svg>

    如您所见,位置值不再是百分比(将像素乘以百分比 does not work ,但只有1的一小部分。我希望这对你有用。