Is there a way to use use text as the background with CSS?

前端 未结 8 667
暖寄归人
暖寄归人 2020-11-28 03:48

I would like to use dynamic text as background of certain elements in my tag. Because of this, I can use images (dynamic text). How do I do it with just CSS or JavaScript?

相关标签:
8条回答
  • 2020-11-28 04:27

    @Ciro

    You can break the inline svg code with back-slash "\"

    Tested with the code below in Chrome 54 and Firefox 50

    body {
        background: transparent;
        background-attachment:fixed;
        background-image: url(
        "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
        <rect x='0' y='0' width='170' height='50' style='stroke:white; fill:gray; stroke-opacity: 0.3; stroke-width: 3px; fill-opacity: 0.7; stroke-dasharray: 10 5; stroke-linecap=round; '/> \
        <text x='85' y='30' style='fill:lightBlue; text-anchor: middle' font-size='16' transform='rotate(10,85,25)'>I love SVG!</text></svg>");
    }
    

    I even Tested this,

    background-image: url("\
    data:image/svg+xml;utf8, \
      <svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='170px' height='50px'> \
        <rect x='0' y='0' width='170' height='50'\
          style='stroke:white; stroke-width: 3px; stroke-opacity: 0.3; \
                 stroke-dasharray: 10 5; stroke-linecap=round; \
                 fill:gray;  fill-opacity: 0.7; '/> \
        <text x='85' y='30' \
          style='fill:lightBlue; text-anchor: middle' font-size='16' \
          transform='rotate(10,85,25)'> \
          I love SVG! \
        </text> \
      </svg>\
    ");
    

    and it works (at least in Chrome 54 & Firefox 50 ==> usage in NWjs & Electron guarenteed)

    0 讨论(0)
  • 2020-11-28 04:30

    You could make the element containing the bg text have a lower stacking order ( z-index, position ) and possibly even set opacity. So the element you need on top would need a higher stacking order ( z-index:5; position:relative; for ex ) and the element behind would need something lower ( default or just a lower z-index like 3 and position:relative; ).

    0 讨论(0)
提交回复
热议问题