Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create transparent text on non-transparent background

Tags:

css

Imagine that: there is a background assigned to "body" and a white "div" with a text inside of it. And this text is so that we can see the background through it. How to implement that with CSS? Like this:enter image description here

like image 491
Eugene Beliaev Avatar asked Jan 19 '26 05:01

Eugene Beliaev


1 Answers

You can use SVG to create a mask with a rect element for the white background and a text element for transparent text part.

body {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('http://blog.oxforddictionaries.com/wp-content/uploads/mountain-names.jpg');
  background-size: cover;
  height: 100vh;
  background-position: center;
  font-family: 'Open Sans', sans-serif;
}

svg {
  width: 300px;
  height: 100px;
}
svg text {
  text-anchor: middle;
}
svg #overlay {
  fill: white;
  opacity: 0.7;
}
svg #text {
  font-size: 40px;
  font-weight: bold;
}

svg #r {
  fill: white;
  mask: url(#mask);
}
<svg>
  <defs>
    <mask id="mask" x="0" y="0" width="100%" height="100%">
      <rect id="overlay" x="0" y="0" width="100%" height="100%" />
      <text id="text" x="50%" y="0" dy="65px">Some text</text>
    </mask>
  </defs>
  <rect id="r" x="0" y="0" width="100%" height="100%" />
</svg>

Update: To create full element size overlay with transparent text you can use position: relative on parent element and position: absolute on svg and set mask height and width to 100%. To center the text you can use dy: 50% with alignment-baseline: middle; and text-anchor: middle;

body {
  margin: 0;
  padding: 0;
}

.element {
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('http://blog.oxforddictionaries.com/wp-content/uploads/mountain-names.jpg');
  background-size: cover;
  height: 100vh;
  background-position: center;
  font-family: 'Open Sans', sans-serif;
  position: relative;
}

section {
  height: 100vh;
  background: lightgreen;
}

svg {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

svg text {
  text-anchor: middle;
  alignment-baseline: middle;
  font-size: 40px;
  font-weight: bold;
}

svg #overlay {
  fill: white;
  opacity: 0.7;
}

svg #r {
  fill: white;
  mask: url(#mask);
}
<div class="element">
  <svg>
    <defs>
      <mask id="mask" x="0" y="0" width="100%" height="100%">
        <rect id="overlay" x="0" y="0" width="100%" height="100%" />
        <text  id="text" x="50%" y="0" dy="50%">Some text here</text>
      </mask>
    </defs>
    <rect id="r" x="0" y="0" width="100%" height="100%" />
  </svg>
</div>

<section></section>
like image 95
Nenad Vracar Avatar answered Jan 21 '26 21:01

Nenad Vracar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!