csscss-content

Add svg to content property


I want to add the svg link inside the content property. Can I do it?

.selectedItem::before{
  content: " any svg link ";


Solution

  • Absolutely, I use this (or rather a variant of it) all the time:

    .selected-item:before {
      content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' class='whirlocal-pin whirlocal-pin-2' viewBox='0 0 300 400'%3E%3Cdefs%3E%3Cstyle%3E.shape,.swipe-left%7Bfill:%230095ee%7D.shape%7Bfill-rule:evenodd%7D.swipe-right%7Bfill:url(%23linear-gradient)%7D%3C/style%3E%3ClinearGradient id='linear-gradient' x1='187.984' x2='187.984' y2='201' gradientUnits='userSpaceOnUse'%3E%3Cstop offset='0' stop-color='%230350b9'%3E%3C/stop%3E%3Cstop offset='1' stop-color='%230095ee'%3E%3C/stop%3E%3C/linearGradient%3E%3C/defs%3E%3Cpath id='shape' data-name='Outer Pin' class='shape' d='M149.95,400C119.012,320.886,76.928,285.143,45.216,250.9,30.746,235.281,18.435,219.97,10.329,201,3.795,185.7-.008,168.023-0.008,145.882-0.008,65.314,67.131,0,149.95,0S299.908,65.314,299.908,145.882C299.908,255.686,206.386,255.686,149.95,400ZM102.314,98.408c27.056-27.056,70.339-27.64,96.675-1.3s25.752,69.619-1.3,96.675c-24.845,24.845-63.373,27.368-89.9,7.221a66.106,66.106,0,0,1-6.778-5.917C74.675,168.747,75.259,125.464,102.314,98.408Z'%3E%3C/path%3E%3Cpath id='swipe-right' data-name='Outer Pin copy' class='swipe-right' d='M101.053,195.083C74.706,168.747,45.219,96.8,150.013,0H149.95c82.82,0,149.958,65.314,149.958,145.882,0,22.088-3.4,39.848-9.908,55.118l-100.734-.009a71.69,71.69,0,0,0,8.42-7.212c27.055-27.056,27.639-70.339,1.3-96.674s-69.619-25.752-96.675,1.3-27.639,70.339-1.3,96.675c2.152,2.152,2.2,2.152.042,0'%3E%3C/path%3E%3C/svg%3E");
      width: 100px;
      height: 100px;
      display: block;
    }
    <div class="selected-item"></div>

    You'll need to either upload your SVG and use the URI to it: url('/assets/svg/mysvg.svg');, or you'll need to URL encode it, remove double quotes, and convert it to a data-image like I've shown you in the example above. Writing a JS, PHP, etc. function for that would be trivial - but if you need a one-off copy/paste data-image, you can just use this tool: https://yoksel.github.io/url-encoder/