CSS美化半个字符的巧妙方法

2020-04-27 15:02:58易采站长站整理

        }   
  
        // Write to DOM only once   
        $el.append(output);   
    });   
});   
  

这样,不论是一段文字还是整篇文字,我们都能一次搞定,不必手工一个一个的设置,也不必一个一个的做图!

高级做法:左右半个字符都用伪元素生成

上面我们的做法中,文字的左半边是用:before伪元素生成的,而右半边使用的是原文字。但实际上我们可以将左右两边都用伪元素生成——右半边用:after实现。

CSS代码

CSS Code复制内容到剪贴板

.halfStyle {   
    position:relative;   
    display:inline-block;   
    font-size:80px; /* or any font size will work */  
    color: transparent; /* hide the base character */  
    overflow:hidden;   
    whitewhite-space: pre; /* to preserve the spaces from collapsing */  
}   
.halfStyle:before { /* creates the left part */  
    display:block;   
    z-index:1;   
    position:absolute;   
    top:0;   
    width: 50%;   
    content: attr(data-content); /* dynamic content for the pseudo element */  
    overflow:hidden;   
    pointer-events: none; /* so the base char is selectable by mouse */  
    color: #f00; /* for demo purposes */  
    text-shadow: 2px -2px 0px #af0; /* for demo purposes */  
}   
.halfStyle:after { /* creates the right part */  
    display:block;   
    direction: rtl; /* very important, will make the width to start from right */  
    position:absolute;   
    z-index:2;   
    top:0;