Home > Net >  How to cut part of SVG with css?
How to cut part of SVG with css?

Time:12-31

I have a logo in SVG (minimal example):

<svg  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 695 189.08">
    <path d="1....">
    <path d="2....">
    <path d="3....">
</svg>

I want to remove the text (logotype) from svg element when the .hide-text class is present. Currently, I'm doing this with:

.hide-text {
   path {
      &:nth-child(n 3):nth-child(-n 10), &:last-child { /* paths for text part */
         display: none;
         /* visibility: hidden; */
         /* opacity: 0; */
         /* d: path('0') !important; */
      }
   }
}

The problem is that all of them just "hide" the path & the parent SVG element is still taking space!
(d only works in Chrome & that's not good)

How can I remove some paths using css?

CodePudding user response:

Might be much simpler to load two logos (one with text and one without), and add a display: none to one of them based on the existence of the class. This will remove it from page unlike with visibility: hidden

<div >
    <svg ></svg>
    <svg ></svg>
</div>

<style>
    .container-div:not(.hide-text) > .logo-no-text {
        display: none;
    }
    .container-div:not(.hide-text) > .logo-text {
        display: block;
    }
    .container-div.hide-text > .logo-text {
        display: none;
    }
    .container-div.hide-text > .logo-no-text {
        display: block;
    }
</style>

CodePudding user response:

If you know the width/height of the SVG you can hide part of the SVG using a negative margin. In the example I have two SVG elements with the same content except that the last has the class name .hide-text.

So, if you know the dimensions and the portion that needs to be cut off you can use this technique.

svg {
  width: 300px;
}

.hide-text {
  margin: 0 0 -50px;
}

.hide-text rect:nth-child(2) {
  display: none;
}
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 200">
  <rect width="100%" height="50%" fill="navy"/>
  <rect width="100%" height="50%" fill="orange" transform="translate(0 100)"/>
</svg>
<div>Text</div>
<hr/>
<svg  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 200">
  <rect width="100%" height="50%" fill="navy"/>
  <rect width="100%" height="50%" fill="orange" transform="translate(0 100)"/>
</svg>
<div>Text</div>

  • Related