programing

배경에서 잘라낸 투명한 텍스트

nasanasas 2020. 9. 22. 08:16
반응형

배경에서 잘라낸 투명한 텍스트


CSS를 사용하여 다음 이미지와 같은 배경 효과 에서 투명한 텍스트를 잘라내 는 방법이 있습니까?
이미지가 텍스트를 대체하기 때문에 귀중한 SEO를 모두 잃는 것은 슬픈 일입니다.

배경에서 잘라낸 투명한 텍스트

처음에는 그림자를 생각했지만 아무것도 알아낼 수 없습니다 ...

이미지는 사이트 배경, 절대 위치 <img>태그입니다.


css3에서는 가능하지만 모든 브라우저에서 지원되지는 않습니다.

배경 클립 사용 : 텍스트; 텍스트에 배경을 사용할 수 있지만 페이지의 배경에 맞춰 정렬해야합니다.

body {
    background: url(http://www.color-hex.com/palettes/26323.png) repeat;
    margin:10px;
}
h1 { 
    background-color:#fff;
    overflow:hidden;
    display:inline-block; 
    padding:10px; 
    font-weight:bold;
    font-family:arial;
    color:transparent;
    font-size:200px;
}span { 
    background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    display:block;
}
<h1><span>ABCDEFGHIKJ</span></h1>

http://jsfiddle.net/JGPuZ/1337/

자동 정렬

약간의 자바 스크립트를 사용하면 배경을 자동으로 정렬 할 수 있습니다.

$(document).ready(function(){
  var position = $("h1").position(); //Position of the header in the webpage
  var padding = 10; //Padding set to the header
  var left = position.left + padding;
  var top = position.top + padding;
  $("h1").find("span").css("background-position","-"+left+"px -"+top+"px"); 
});
body {
    background: url(http://www.color-hex.com/palettes/26323.png) repeat;
    margin:10px;
}
h1 { 
    background-color:#fff;
    overflow:hidden;
    display:inline-block; 
    padding:10px; 
    font-weight:bold;
    font-family:arial;
    color:transparent;
    font-size:200px;
}span { 
    background: url(http://www.color-hex.com/palettes/26323.png) -20px -20px repeat;
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><span>ABCDEFGHIKJ</span></h1>
http://jsfiddle.net/JGPuZ/1336/


CSS로 가능하지만 더 나은 방법은 SVG 마스킹 과 함께 인라인 SVG 를 사용하는 것 입니다. 이 접근 방식은 CSS보다 몇 가지 장점이 있습니다.

CodePen 데모 : SVG 텍스트 마스크

투명 텍스트 클리핑 배경

body,html{height:100%;margin:0;padding:0;}
body{
  background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
  background-size:cover;
  background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
  <defs>
    <mask id="mask" x="0" y="0" width="100" height="50">
      <rect x="0" y="0" width="100" height="40" fill="#fff"/>
      <text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
      <text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
    </mask>
  </defs>
  <rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>    
</svg>

텍스트를 선택 및 검색 가능하게 만드는 것을 목표로하는 경우 <defs>태그 외부에 포함해야합니다 . 다음 예제는 <use>태그로 투명한 텍스트를 유지하는 방법을 보여줍니다 .

body,html{height:100%;margin:0;padding:0;}
body{
  background:url('https://farm9.staticflickr.com/8760/17195790401_94fcf60556_c.jpg');
  background-size:cover;
  background-attachment:fixed;
}
svg{width:100%;}
<svg viewbox="0 0 100 60">
  <defs>
    <g id="text">
      <text text-anchor="middle" x="50" y="18" dy="1">SVG</text>
      <text text-anchor="middle" x="50" y="30" dy="1">Text mask</text>
    </g>
    <mask id="mask" x="0" y="0" width="100" height="50">
      <rect x="0" y="0" width="100" height="40" fill="#fff"/>
      <use xlink:href="#text" />
    </mask>
  </defs>
  <rect x="5" y="5" width="90" height="30" mask="url(#mask)" fill-opacity="0.5"/>
  <use xlink:href="#text" mask="url(#mask)" />
</svg>


대부분의 최신 브라우저 (예 : edge 제외)에서 작동하는 한 가지 방법은 검은 색 배경으로 만 사용하는 것입니다.

background: black;
color: white;
mix-blend-mode: multiply;

텍스트 요소에 넣은 다음 그 뒤에 원하는 배경을 넣으십시오. 곱하기는 기본적으로 0-255 색상 코드를 0-1에 매핑 한 다음 그 뒤에있는 값을 곱하므로 검정은 흑백으로 유지되고 흰색은 1을 곱하고 효과적으로 투명 해집니다. http://codepen.io/nic_klaassen/full/adKqWX/


그것은 이다 가능하지만, 지금까지 유일한 웹킷 기반 브라우저 (크롬 프로젝트를 기반으로 크롬, 사파리, 멜트, 아무것도.)

비결은 본문과 동일한 배경을 가진 흰색 -webkit- background-clip: text;요소를 내부 요소에 넣은 다음 기본적으로 "배경을 텍스트 너머로 확장하지 마십시오"를 의미하는 내부 요소에 사용하고 투명한 텍스트를 사용하는 것입니다.

section
{
    background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
    width: 100%;
    height: 300px;
}

div
{
    background: rgba(255, 255, 255, 1);
    color: rgba(255, 255, 255, 0);

    width: 60%;
    heighT: 80%;
    margin: 0 auto;
    font-size: 60px;
    text-align: center;
}

p
{
    background: url(http://norcaleasygreen.com/wp-content/uploads/2012/11/turf-grass1.jpg);
    -webkit-background-clip: text;
}

http://jsfiddle.net/BWRsA/


I guess you could achieve something like that using background-clip, but I haven't tested that yet.

See this example:
http://www.css3.info/wp-content/uploads/2008/03/webkit-backgroundcliptext_color.html
(Webkit only, I don't know yet how to change the black background to a white one)


I just discovered a new way to do this while messing around, I'm not entirely sure how it works ( if someone else wants to explain please do ).

It seems to work very well, and requires no double backgrounds or JavaScript.

Here's the code: JSFIDDLE

body {
  padding: 0;
  margin: 0;
}

div {
  background: url(http://www.color-hex.com/palettes/26323.png) repeat;
  width: 100vw;
  height: 100vh;
}

body::before {
  content: '$ALPHABET';
  left: 0;
  top: 0;
  position: absolute;
  color: #222;
  background-color: #fff;
  padding: 1rem;
  font-family: Arial;
  z-index: 1;
  mix-blend-mode: screen;
  font-weight: 800;
  font-size: 3rem;
  letter-spacing: 1rem;
}
<div></div>


You can use an inverted / negative / reverse font and apply it with the font-face="…" CSS rule. You might have to play with letter spacing to avoid small white gaps between letters.

If you do not require a specific font, it's simple. Download a likeable one, for example from this collection of inverted fonts.

If you require a specific font (say, "Open Sans"), it's difficult. You have to convert your existing font into an inverted version. This is possible manually with Font Creator, FontForge etc., but of course we want an automated solution. I could not find instructions for that yet, but some hints:


You can use myadzel's Patternizer jQuery plugin to achieve this effect across browsers. At this time, there is no cross-browser way to do this with just CSS.

You use Patternizer by adding class="background-clip" to HTML elements where you want the text to be painted as an image pattern, and specify the image in an additional data-pattern="…" attribute. See the source of the demo. Patternizer will create an SVG image with pattern-filled text and underlay it to the transparently rendered HTML element.

If, as in the question's example image, the text fill pattern should be a part of a background image extending beyond the "patternized" element, I see two options (untested, my favourite first):

  • Use masking instead of a background image in the SVG. As in web-tiki's answer, to which using Patternizer will still add automatic generation of the SVG and an invisible HTML element on top that allows text selection and copying.
  • Or use automatic alignment of the pattern image. Can be done with JavaScript code similar to the one in Gijs's answer.

just put that css

    .banner-sale-1 .title-box .title-overlay {
      font-weight: 900;
      overflow: hidden;
      margin: 0;
      padding-right: 10%;
      padding-left: 10%;
      text-transform: uppercase;
      color: #080404;
      background-color: rgba(255, 255, 255, .85);

      /* that css is the main think (mix-blend-mode: lighten;)*/
      mix-blend-mode: lighten;

    }

데모 스크린 샷

I needed to make text that looked exactly like it does in the original post, but I couldn't just fake it by lining up backgrounds, because there's some animation behind the element. Nobody seems to have suggested this yet, so here's what I did: (Tried to make it as easy to read as possible.)

var el = document.body; //Parent Element. Text is centered inside.
var mainText = "THIS IS THE FIRST LINE"; //Header Text.
var subText = "THIS TEXT HAS A KNOCKOUT EFFECT"; //Knockout Text.
var fontF = "Roboto, Arial"; //Font to use.
var mSize = 42; //Text size.

//Centered text display:
var tBox = centeredDiv(el), txtMain = mkDiv(tBox, mainText), txtSub = mkDiv(tBox),
ts = tBox.style, stLen = textWidth(subText, fontF, mSize)+5; ts.color = "#fff";
ts.font = mSize+"pt "+fontF; ts.fontWeight = 100; txtSub.style.fontWeight = 400;

//Generate subtext SVG for knockout effect:
txtSub.innerHTML =
"<svg xmlns='http://www.w3.org/2000/svg' width='"+stLen+"px' height='"+(mSize+11)+"px' viewBox='0 0 "+stLen+" "+(mSize+11)+"'>"+
    "<rect x='0' y='0' width='100%' height='100%' fill='#fff' rx='4px' ry='4px' mask='url(#txtSubMask)'></rect>"+
    "<mask id='txtSubMask'>"+
        "<rect x='0' y='0' width='100%' height='100%' fill='#fff'></rect>"+
        "<text x='"+(stLen/2)+"' y='"+(mSize+6)+"' font='"+mSize+"pt "+fontF+"' text-anchor='middle' fill='#000'>"+subText+"</text>"+
    "</mask>"+
"</svg>";

//Relevant Helper Functions:
function centeredDiv(parent) {
    //Container:
    var d = document.createElement('div'), s = d.style;
    s.display = "table"; s.position = "relative"; s.zIndex = 999;
    s.top = s.left = 0; s.width = s.height = "100%";
    //Content Box:
    var k = document.createElement('div'), j = k.style;
    j.display = "table-cell"; j.verticalAlign = "middle";
    j.textAlign = "center"; d.appendChild(k);
    parent.appendChild(d); return k;
}
function mkDiv(parent, tCont) {
    var d = document.createElement('div');
    if(tCont) d.textContent = tCont;
    parent.appendChild(d); return d;
}
function textWidth(text, font, size) {
    var canvas = window.textWidthCanvas || (window.textWidthCanvas = document.createElement("canvas")),
    context = canvas.getContext("2d"); context.font = size+(typeof size=="string"?" ":"pt ")+font;
    return context.measureText(text).width;
}

당신의 window.onload에 그것을 던져서 몸의 배경을 당신의 이미지로 설정하고 마술이 일어나는 것을 지켜보십시오!


지금 CSS로는 불가능합니다.

가장 좋은 방법은 이미지 (아마도 PNG)를 사용하고 그 위에 좋은 대체 / 제목 텍스트를 배치하는 것입니다.

또는 SPAN 또는 DIV를 사용하고 SEO 목적으로 원하는 텍스트가있는 이미지를 배경으로 사용할 수 있지만 화면 밖으로 텍스트 들여 쓰기를 할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/13932946/transparent-text-cut-out-of-background

반응형