SVG Knockout Text

Avatar of Geoff Graham
Geoff Graham on (Updated on )

The idea here is to imagine three layers stacked on top of one another where the top layer is used to cut out a shape in the second layer to reveal the third layer.

If the text on the top layer of the diagram above were the shape we are cutting out of the second layer, then the following image illustrates the concept of knockout text.

SVG Snippet

Here is a snippet that sets up the bottom layer (.knockout) that the knockout text will reveal, the middle layer (.knockout-text-bg) that we are cutting out of, and the top layer (.knockout-text) that contains the SVG text that will act as a mask to cut out the second layer.

<div class="knockout">
  
  <svg class="knockout-text-container" width="100%" height="100%">
    
    <rect class="knockout-text-bg" width="100%" height="100%" fill="#000" x="0" y="0" fill-opacity="1" mask="url(#knockout-text)" />
    
    <mask id="knockout-text">
      <rect width="100%" height="100%" fill="#fff" x="0" y="0" />
      <text x="50%" y="50%" fill="#000" text-anchor="middle">Knock Out Text</text>
    </mask>
    
  </svg>
  
</div>

The <text> coordinates are totally arbitrary in this example and can be adjusted to suit the actual size and placement of the text being added.

Note that the fill of the second layer is black and the fill of the top layer is white. That is how masks work: white is the perfect contrast to black and will hide the black parts. We could make the top layer a totally different color and it would not completely hide the black, but allow some of it to slip through.

CSS Styling

The rest is CSS styling. For example, we can add a background gradient to the bottom layer and style up the font size to get more of a dramatic effect.

.knockout {
  /* Ensure the bottom layer is full screen */
  height: 100vh;
  width: 100%;
  /* Add a colorful texture and cutom font-styling */
  background-image: linear-gradient(to left, #ff4e50 , #f9d423);
  text-transform: uppercase;
}

/* Knockout text font sizing for each line */

text:nth-child(2) {
  font-size: 5em;
}

text:nth-child(3) {
  font-size: 5.1em;
}

text:nth-child(4) {
  font-size: 15em;
}

See the Pen SVG Knock Out Text by Geoff Graham (@geoffgraham) on CodePen.