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


CSS美化半个字符的基本思路
CSS代码
.halfStyle {position:relative;display:inline-block;font-size:80px; /* 任何宽度都可以 */color: black; /* 任何颜色,或透明 */overflow:hidden;white-space: pre; /* 处理空格 */}.halfStyle:before {display:block;z-index:1;position:absolute;top:0;left:0;width: 50%;content: attr(data-content); /* 伪元素的动态获取内容 */overflow:hidden;color: #f00;}
HTML代码
单个字符
风流倜傥用脚本自动美化:
恋爱容易婚姻不易,且行且珍惜。
jQuery(function($) {var text, chars, $el, i, output;// 遍历所有字符$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');// Set the screen-reader text$el.html('' + text + '');// Reset output for appendingoutput = '';// Iterate over all chars in the textfor (i = 0; i < chars.length; i++) {// Create a styled element for each character and append to containeroutput += '';}// Write to DOM only once$el.append(output);});});
高级做法:左右半个字符都用伪元素生成
CSS代码
.halfStyle {position:relative;display:inline-block;font-size:80px; /* or any font size will work */color: transparent; /* hide the base character */overflow:hidden;white-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;left:50%;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: #000; /* for demo purposes */text-shadow: 2px 2px 0px #0af; /* for demo purposes */}


评论
