是否可以将CSS应用于半个字符?

我在寻找什么:

一种为字符一半设置样式的方法。(在这种情况下,一半的字母是透明的)

我目前正在搜索和尝试(没有运气):

  • 为字符/字母的一半设置样式的方法
  • 使用CSS或JavaScript对字符的一部分进行样式化
  • 将CSS应用于50%的字符

下面是我想得到的一个例子。

x

是否存在CSS或JavaScript解决方案,或者我必须求助于图像?我宁愿不走图像路线,因为此文本最终将动态生成。


更新:

很多人问我为什么要设计半个角色的样式,我的答案是这样的。我所在的城市最近花了25万美元为自己定义了一个新的“品牌”。他们想出了这个标志。很多人抱怨简单和缺乏创造力,并继续这样做。我的目标是想出这个网站作为一个笑话。输入“哈利法克斯”,你就会明白我的意思。

286511 次浏览

我能得到的最接近:

$(function(){$('span').width($('span').width()/2);$('span:nth-child(2)').css('text-indent', -$('span').width());});
body{font-family: arial;}span{display: inline-block;overflow: hidden;}span:nth-child(2){color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>X</span><span>X</span>

演示:http://jsfiddle.net/9wxfY/2/

这是一个只使用一个跨度的版本:http://jsfiddle.net/9wxfY/4/

在此处输入图片描述


我刚刚完成了插件的开发,它可供大家使用!希望你会喜欢它。

查看项目github-查看项目网站.(所以你可以看到所有的分割样式)

用法

首先,确保包含jQuery库。获取最新jQuery版本的最佳方法是更新您的head标签:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

下载文件后,请确保将它们包含在您的项目中:

<link rel="stylesheet" type="text/css" href="css/splitchar.css"><script type="text/javascript" src="js/splitchar.js"></script>

置标

您所要做的就是将类splitchar分配给包装文本的元素,然后是所需的样式。例如

<h1 class="splitchar horizontal">Splitchar</h1>

完成所有这些之后,只需确保您在文档就绪文件中调用jQuery函数,如下所示:

$(".splitchar").splitchar();

自定义

为了使文本看起来完全像你想要的那样,你所要做的就是像这样应用你的设计:

.horizontal { /* Base CSS - e.g font-size */ }.horizontal:before { /* CSS for the left half */ }.horizontal:after { /* CSS for the right half */ }


就是这样!现在您已经设置了Splitchar插件。有关它的更多信息,请访问http://razvanbalosin.com/Splitchar.js/

示例


JSFiddle演示

我们将仅使用CSS伪选择器来完成它!

这种技术将适用于动态生成的内容和不同的字体大小和宽度。

超文本标记语言:

<div class='split-color'>Two is better than one.</div>

css:

.split-color > span {white-space: pre-line;position: relative;color: #409FBF;}
.split-color > span:before {content: attr(data-content);pointer-events: none;  /* Prevents events from targeting pseudo-element */position: absolute;overflow: hidden;color: #264A73;width: 50%;z-index: 1;}

要包装动态生成的字符串,您可以使用这样的函数:

// Wrap each letter in a span tag and return an HTML string// that can be used to replace the original textfunction wrapString(str) {var output = [];str.split('').forEach(function(letter) {var wrapper = document.createElement('span');wrapper.dataset.content = wrapper.innerHTML = letter;
output.push(wrapper.outerHTML);});
return output.join('');}
// Replace the original text with the split-color textwindow.onload = function() {var el  = document.querySelector('.split-color'),txt = el.innerHTML;    
el.innerHTML = wrapString(txt);}

有限的CSS和jQuery解决方案

我不确定这个解决方案有多优雅,但它将所有内容都减半:http://jsfiddle.net/9wxfY/11/

否则,我为你创建了一个很好的解决方案……你需要做的就是为你的超文本标记语言:

看看这个最新的,准确的,截至2016年6月13日的编辑:http://jsfiddle.net/9wxfY/43/

至于CSS,它非常有限…你只需要将它应用于:nth-child(even)

$(function(){var $hc = $('.half-color');var str = $hc.text();$hc.html("");
var i = 0;var chars;var dupText;
while(i < str.length){chars = str[i];if(chars == " ") chars = "&nbsp;";dupText = "<span>" + chars + "</span>";
var firstHalf = $(dupText);var secondHalf = $(dupText);
$hc.append(firstHalf)$hc.append(secondHalf)
var width = firstHalf.width()/2;
firstHalf.width(width);secondHalf.css('text-indent', -width);
i++;}});
.half-color span{font-size: 2em;display: inline-block;overflow: hidden;}.half-color span:nth-child(even){color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="half-color">This is a sentence</div>

现在在GitHub上作为插件!

在此处输入图像描述随意分叉和改进。

Demo|下载Zip|Half-Style.com(重定向到GitHub)


  • 纯CSS对于单个字符
  • 用于跨文本或多个字符自动化的JavaScript
  • 保留盲人或视觉屏幕阅读器的文本可访问性受损

第1部分:基本解决方案

文本的半样式

演示:http://jsfiddle.net/arbel/pd9yB/1694/


这适用于任何动态文本或单个字符,并且都是自动化的。您需要做的就是在目标文本上添加一个类,其余的就会处理好。

此外,为盲人或视障人士的屏幕阅读器保留了原始文本的可访问性。

单个字符的解释:

纯CSS。您需要做的就是将.halfStyle类应用于包含您想要半样式的字符的每个元素。

对于每个包含字符的跨度元素,您可以创建一个数据属性,例如这里的data-content="X",并且在伪元素上使用content: attr(data-content);,因此.halfStyle:before类将是动态的,您不需要为每个实例硬编码。

对任何文本的解释:

只需将textToHalfStyle类添加到包含文本的元素中。


// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.halfStyle {position: relative;display: inline-block;font-size: 80px; /* or any font size will work */color: black; /* or transparent, any color */overflow: hidden;white-space: pre; /* to preserve the spaces from collapsing */}
.halfStyle:before {display: block;z-index: 1;position: absolute;top: 0;left: 0;width: 50%;content: attr(data-content); /* dynamic content for the pseudo element */overflow: hidden;color: #f00;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示


第2部分:高级解决方案-独立的左右部分

文本上的半样式-高级-带文本阴影

使用此解决方案,您可以单独和独立地为左右部分设置样式

一切都是一样的,只有更高级的CSS才能发挥作用。

jQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.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 */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示



第3部分:混合匹配和改进

现在我们知道什么是可能的,让我们创建一些变化。


-水平半部分

  • 没有文本阴影:

    水平半部分-无文本阴影

  • 每个半部分独立的文本阴影的可能性:

    半样式-水平半部分-带文本阴影

// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.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 top part */display: block;z-index: 2;position: absolute;top: 0;height: 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 bottom part */display: block;position: absolute;z-index: 1;top: 0;height: 100%;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 */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示



-垂直1/3部分

  • 没有文本阴影:

    半样式-垂直1/3部分-无文本阴影

  • 每个1/3部分独立的文本阴影的可能性:

    半样式-垂直1/3部分-带文本阴影

// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.halfStyle { /* base char and also the right 1/3 */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 */color: #f0f; /* for demo purposes */text-shadow: 2px 2px 0px #0af; /* for demo purposes */}
.halfStyle:before { /* creates the left 1/3 */display: block;z-index: 2;position: absolute;top: 0;width: 33.33%;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 middle 1/3 */display: block;z-index: 1;position: absolute;top: 0;width: 66.66%;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 #af0; /* for demo purposes */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示



-水平1/3部分

  • 没有文本阴影:

    半样式-水平1/3部分-无文本阴影

  • 每个1/3部分独立的文本阴影的可能性:

    半样式-水平1/3部分-带文本阴影

// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.halfStyle { /* base char and also the bottom 1/3 */position: relative;display: inline-block;font-size: 80px; /* or any font size will work */color: transparent;overflow: hidden;white-space: pre; /* to preserve the spaces from collapsing */color: #f0f;text-shadow: 2px 2px 0px #0af; /* for demo purposes */}
.halfStyle:before { /* creates the top 1/3 */display: block;z-index: 2;position: absolute;top: 0;height: 33.33%;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 #fa0; /* for demo purposes */}
.halfStyle:after { /* creates the middle 1/3 */display: block;position: absolute;z-index: 1;top: 0;height: 66.66%;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 #af0; /* for demo purposes */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示



-HalfStyle改进@KevinGranger

半风格-凯文格兰杰

// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
body {background-color: black;}
.textToHalfStyle {display: block;margin: 200px 0 0 0;text-align: center;}
.halfStyle {font-family: 'Libre Baskerville', serif;position: relative;display: inline-block;width: 1;font-size: 70px;color: black;overflow: hidden;white-space: pre;text-shadow: 1px 2px 0 white;}
.halfStyle:before {display: block;z-index: 1;position: absolute;top: 0;width: 50%;content: attr(data-content); /* dynamic content for the pseudo element */overflow: hidden;color: white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示



-PeelingStyle对HalfStyle的改进@陈志立

半风格-SamTremaine

// jQuery for automated modejQuery(function($) {var text, chars, $el, i, output;
// Iterate over all class occurences$('.textToHalfStyle').each(function(idx, el) {$el = $(el);text = $el.text();chars = text.split('');
// Set the screen-reader text$el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + text + '</span>');
// 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 += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';}
// Write to DOM only once$el.append(output);});});
.halfStyle {position: relative;display: inline-block;font-size: 68px;color: rgba(0, 0, 0, 0.8);overflow: hidden;white-space: pre;transform: rotate(4deg);text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);}
.halfStyle:before { /* creates the left part */display: block;z-index: 1;position: absolute;top: -0.5px;left: -3px;width: 100%;content: attr(data-content);overflow: hidden;pointer-events: none;color: #FFF;transform: rotate(-4deg);text-shadow: 0px 0px 1px #000;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p>Single Characters:</p><span class="halfStyle" data-content="X">X</span><span class="halfStyle" data-content="Y">Y</span><span class="halfStyle" data-content="Z">Z</span><span class="halfStyle" data-content="A">A</span>
<hr/><p>Automated:</p>
<span class="textToHalfStyle">Half-style, please.</span>

jsfiddle演示samtremaine.co.uk



第4部分:准备生产

自定义不同的半样式样式集可以用于同一页面上所需的元素。您可以定义多个样式集并告诉插件使用哪一个。

该插件在目标.textToHalfStyle元素上使用数据属性data-halfstyle="[-CustomClassName-]",并自动进行所有必要的更改。

因此,只需在包含文本的元素上添加textToHalfStyle class和data属性data-halfstyle="[-CustomClassName-]"。插件将完成其余的工作。

半样式-同一页上的多个

此外,CSS样式集的类定义与上面提到的[-CustomClassName-]部分匹配,并链接到.halfStyle,因此我们将有.halfStyle.[-CustomClassName-]

jQuery(function($) {var halfstyle_text, halfstyle_chars, $halfstyle_el, halfstyle_i, halfstyle_output, halfstyle_style;
// Iterate over all class occurrences$('.textToHalfStyle').each(function(idx, halfstyle_el) {$halfstyle_el = $(halfstyle_el);halfstyle_style = $halfstyle_el.data('halfstyle') || 'hs-base';halfstyle_text = $halfstyle_el.text();halfstyle_chars = halfstyle_text.split('');
// Set the screen-reader text$halfstyle_el.html('<span style="position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);">' + halfstyle_text + '</span>');
// Reset output for appendinghalfstyle_output = '';
// Iterate over all chars in the textfor (halfstyle_i = 0; halfstyle_i < halfstyle_chars.length; halfstyle_i++) {// Create a styled element for each character and append to containerhalfstyle_output += '<span aria-hidden="true" class="halfStyle ' + halfstyle_style + '" data-content="' + halfstyle_chars[halfstyle_i] + '">' + halfstyle_chars[halfstyle_i] + '</span>';}
// Write to DOM only once$halfstyle_el.append(halfstyle_output);});});
/* start half-style hs-base */
.halfStyle.hs-base {position: relative;display: inline-block;font-size: 80px; /* or any font size will work */overflow: hidden;white-space: pre; /* to preserve the spaces from collapsing */color: #000; /* for demo purposes */}
.halfStyle.hs-base:before {display: block;z-index: 1;position: absolute;top: 0;width: 50%;content: attr(data-content); /* dynamic content for the pseudo element */pointer-events: none; /* so the base char is selectable by mouse */overflow: hidden;color: #f00; /* for demo purposes */}
/* end half-style hs-base */

/* start half-style hs-horizontal-third */
.halfStyle.hs-horizontal-third { /* base char and also the bottom 1/3 */position: relative;display: inline-block;font-size: 80px; /* or any font size will work */color: transparent;overflow: hidden;white-space: pre; /* to preserve the spaces from collapsing */color: #f0f;text-shadow: 2px 2px 0px #0af; /* for demo purposes */}
.halfStyle.hs-horizontal-third:before { /* creates the top 1/3 */display: block;z-index: 2;position: absolute;top: 0;height: 33.33%;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 #fa0; /* for demo purposes */}
.halfStyle.hs-horizontal-third:after { /* creates the middle 1/3 */display: block;position: absolute;z-index: 1;top: 0;height: 66.66%;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 #af0; /* for demo purposes */}
/* end half-style hs-horizontal-third */

/* start half-style hs-PeelingStyle, by user SamTremaine on Stackoverflow.com */
.halfStyle.hs-PeelingStyle {position: relative;display: inline-block;font-size: 68px;color: rgba(0, 0, 0, 0.8);overflow: hidden;white-space: pre;transform: rotate(4deg);text-shadow: 2px 1px 3px rgba(0, 0, 0, 0.3);}
.halfStyle.hs-PeelingStyle:before { /* creates the left part */display: block;z-index: 1;position: absolute;top: -0.5px;left: -3px;width: 100%;content: attr(data-content);overflow: hidden;pointer-events: none;color: #FFF;transform: rotate(-4deg);text-shadow: 0px 0px 1px #000;}
/* end half-style hs-PeelingStyle */

/* start half-style hs-KevinGranger, by user KevinGranger on StackOverflow.com*/
.textToHalfStyle.hs-KevinGranger {display: block;margin: 200px 0 0 0;text-align: center;}
.halfStyle.hs-KevinGranger {font-family: 'Libre Baskerville', serif;position: relative;display: inline-block;width: 1;font-size: 70px;color: black;overflow: hidden;white-space: pre;text-shadow: 1px 2px 0 white;}
.halfStyle.hs-KevinGranger:before {display: block;z-index: 1;position: absolute;top: 0;width: 50%;content: attr(data-content); /* dynamic content for the pseudo element */overflow: hidden;color: white;}
/* end half-style hs-KevinGranger
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><p><span class="textToHalfStyle" data-halfstyle="hs-base">Half-style, please.</span></p><p><span class="textToHalfStyle" data-halfstyle="hs-horizontal-third">Half-style, please.</span></p><p><span class="textToHalfStyle" data-halfstyle="hs-PeelingStyle">Half-style, please.</span></p><p style="background-color:#000;"><span class="textToHalfStyle" data-halfstyle="hs-KevinGranger">Half-style, please.</span></p>

jsfiddle演示

是的,你只能用一个字符和CSS来做到这一点:

http://jsbin.com/rexoyice/1/

h1 {display: inline-block;margin: 0; /* for demo snippet */line-height: 1em; /* for demo snippet */font-family: helvetica, arial, sans-serif;font-weight: bold;font-size: 300px;background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);background-clip: text;-webkit-text-fill-color: transparent;}
<h1>X</h1>

Visually, all the examples that use two characters (be it via JS, CSS pseudo elements, or just HTML) look fine, but note that that all adds content to the DOM which may cause accessibility--as well as text selection/cut/paste issues.

一个很好的解决方案,利用background-clip: text支持:http://jsfiddle.net/sandro_paganotti/wLkVt/

span{font-size: 100px;background: linear-gradient(to right, black, black 50%, grey 50%, grey);background-clip: text;-webkit-text-fill-color: transparent;}

这是一个丑陋的画布实现。我尝试了这个解决方案,但结果比我预期的要糟糕,所以还是在这里。

画布示例

$("div").each(function() {var CHARS = $(this).text().split('');$(this).html("");$.each(CHARS, function(index, char) {var canvas = $("<canvas />").css("width", "40px").css("height", "40px").get(0);$("div").append(canvas);var ctx = canvas.getContext("2d");var gradient = ctx.createLinearGradient(0, 0, 130, 0);gradient.addColorStop("0", "blue");gradient.addColorStop("0.5", "blue");gradient.addColorStop("0.51", "red");gradient.addColorStop("1.0", "red");ctx.font = '130pt Calibri';ctx.fillStyle = gradient;ctx.fillText(char, 10, 130);});});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div>Example Text</div>

另一个仅限CSS的解决方案(尽管如果您不想编写特定于字母的CSS,则需要数据属性)。这个更全面(测试过的IE 9/10,Chrome最新和FF最新)

span {position: relative;color: rgba(50,50,200,0.5);}
span:before {content: attr(data-char);position: absolute;width: 50%;overflow: hidden;color: rgb(50,50,200);}
<span data-char="X">X</span>

在此处输入图像描述

我刚刚玩了@Arbel的解决方案:

var textToHalfStyle = $('.textToHalfStyle').text();var textToHalfStyleChars = textToHalfStyle.split('');$('.textToHalfStyle').html('');$.each(textToHalfStyleChars, function(i,v){$('.textToHalfStyle').append('<span class="halfStyle" data-content="' + v + '">' + v + '</span>');});
body{background-color: black;}.textToHalfStyle{display:block;margin: 200px 0 0 0;text-align:center;}.halfStyle {font-family: 'Libre Baskerville', serif;position:relative;display:inline-block;width:1;font-size:70px;color: black;overflow:hidden;white-space: pre;text-shadow: 1px 2px 0 white;}.halfStyle:before {display:block;z-index:1;position:absolute;top:0;width: 50%;content: attr(data-content); /* dynamic content for the pseudo element */overflow:hidden;color: white;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><span class="textToHalfStyle">Dr. Jekyll and M. Hide</span>

.halfStyle {position:relative;display:inline-block;font-size:68px; /* or any font size will work */color: rgba(0,0,0,0.8); /* or transparent, any color */overflow:hidden;white-space: pre; /* to preserve the spaces from collapsing */transform:rotate(4deg);-webkit-transform:rotate(4deg);text-shadow:2px 1px 3px rgba(0,0,0,0.3);}.halfStyle:before {display:block;z-index:1;position:absolute;top:-0.5px;left:-3px;width: 100%;content: attr(data-content); /* dynamic content for the pseudo element */overflow:hidden;color: white;transform:rotate(-4deg);-webkit-transform:rotate(-4deg);text-shadow:0 0 1px black;
}

http://experimental.samtremaine.co.uk/half-style/

你可以用这个代码来做各种有趣的事情——这只是我和我的同事昨晚想出的一个实现。

你也可以使用SVG,如果你愿意:

var title = document.querySelector('h1'),text = title.innerHTML,svgTemplate = document.querySelector('svg'),charStyle = svgTemplate.querySelector('#text');
svgTemplate.style.display = 'block';
var space = 0;
for (var i = 0; i < text.length; i++) {var x = charStyle.cloneNode();x.textContent = text[i];svgTemplate.appendChild(x);x.setAttribute('x', space);space += x.clientWidth || 15;}
title.innerHTML = '';title.appendChild(svgTemplate);
<svg style="display: none; height: 100px; width: 100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"><defs id="FooDefs"><linearGradient id="MyGradient" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="50%" stop-color="blue" /><stop offset="50%" stop-color="red" /></linearGradient></defs><text y="50%" id="text" style="font-size: 72px; fill: url(#MyGradient)"></text></svg>
<h1>This is not a solution X</h1>

http://codepen.io/nicbell/pen/jGcbq

FWIW,这是我的看法,只使用CSS:http://codepen.io/ricardozea/pen/uFbts/

几点说明:

  • 我这样做的主要原因是为了测试自己,看看我是否能够在为OP提供有意义的答案的同时完成角色的一半样式。

  • 我知道这不是一个理想的或最具可扩展性的解决方案,这里的人提出的解决方案更适合“现实世界”的场景。

  • 我创建的CSS代码是基于我脑海中的第一个想法和我自己解决问题的方法。

  • 我的解决方案仅适用于对称字符,如X、A、O、M**它不适用于不对称字符,如B、C、F、K或小写字母。

  • **但是,这种方法使用不对称字符创建了非常有趣的“形状”。尝试将X更改为K或小写字母,例如CSS中的hp:)

超文本标记语言

<span class="half-letter"></span>

SCSS

.half-character {display: inline-block;font: bold 350px/.8 Arial;position: relative;
&:before, &:after {content: 'X'; //Change character heredisplay: inline-block;width: 50%;overflow: hidden;color: #7db9e8;}&:after {position: absolute;top: 0;left: 50%;color: #1e5799;transform: rotateY(-180deg);}}

如果你对此感兴趣,那么Lucas Bebber的Glitch是一个非常相似且超级酷的效果:

输入图片描述

使用一个简单的SASS混合创建,例如

.example-one {font-size: 100px;@include textGlitch("example-one", 17, white, black, red, blue, 450, 115);}

更多细节在Chris Coyer的CSS技巧Lucas Bebber的CoDepen页面

这可以通过CSS:before选择器和content property value来实现。

.halfed, .halfed1 {float: left;}
.halfed, .halfed1 {font-family: arial;font-size: 300px;font-weight: bolder;width: 200px;height: 300px;position: relative; /* To help hold the content value within */overflow: hidden;color: #000;}



.halfed:before, .halfed1:before   {width: 50%; /* How much we'd like to show */overflow: hidden; /* Hide what goes beyond our dimension */content: 'X'; /* Halfed character */height: 100%;position: absolute;color: #28507D;
}


/* For Horizontal cut off */
.halfed1:before   {width: 100%;height: 55%;  
}
<div class="halfed"> X </div>
<div class="halfed1"> X </div>

>在jsFiddle上看到

您可以使用下面的代码。在这个例子中,我使用了h1标签并添加了一个属性data-title-text="Display Text",它将与h1标签文本元素上的不同颜色文本一起出现,这给出了半彩色文本的效果,如下例所示

在此处输入图片描述

body {text-align: center;margin: 0;}
h1 {color: #111;font-family: arial;position: relative;font-family: 'Oswald', sans-serif;display: inline-block;font-size: 2.5em;}
h1::after {content: attr(data-title-text);color: #e5554e;position: absolute;left: 0;top: 0;clip: rect(0, 1000px, 30px, 0);}
<h1 data-title-text="Display Text">Display Text</h1>

对于较短的文本,这样的东西怎么样?

如果您使用循环执行某些操作,使用JavaScript重复字符,它甚至可以适用于更长的文本。无论如何,结果是这样的:

是否可以将CSS应用于一半字符?

p.char {position: relative;display: inline-block;font-size: 60px;color: red;}
p.char:before {position: absolute;content: attr(char);width: 50%;overflow: hidden;color: black;}
<p class="char" char="S">S</p><p class="char" char="t">t</p><p class="char" char="a">a</p><p class="char" char="c">c</p><p class="char" char="k">k</p><p class="char" char="o">o</p><p class="char" char="v">v</p><p class="char" char="e">e</p><p class="char" char="r">r</p><p class="char" char="f">f</p><p class="char" char="l">l</p><p class="char" char="o">o</p><p class="char" char="w">w</p>

只是为了历史上的记录!

我为自己5-6年前的工作想出了一个解决方案,即Gradtext(纯javascript和纯css,没有依赖项)。

技术解释是您可以创建这样的元素:

<span>A</span>

现在,如果你想在文本上进行渐变,你需要创建多个图层,每个图层都单独着色,创建的光谱将说明渐变效果。

例如,看这是<span>中的单词lorem,将导致水平渐变效果(查看示例):

 <span data-i="0" style="color: rgb(153, 51, 34);">L</span><span data-i="1" style="color: rgb(154, 52, 35);">o</span><span data-i="2" style="color: rgb(155, 53, 36);">r</span><span data-i="3" style="color: rgb(156, 55, 38);">e</span><span data-i="4" style="color: rgb(157, 56, 39);">m</span>

你可以继续这样做很长一段时间和很长一段时间。

在此处输入图片描述

但是!

如果您想在文本上创建垂直梯度效果怎么办?

然后还有另一个可能有用的解决方案。我会详细描述。

假设我们再次使用第一个<span>,但是内容不应该是单独的字母;内容应该是整个文本,现在我们将一次又一次地复制相同的<span>(跨度的计数将定义渐变的质量,更大的跨度,更好的结果,但是性能很差)。

<span data-i="6" style="color: rgb(81, 165, 39); overflow: hidden; height: 11.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span><span data-i="7" style="color: rgb(89, 174, 48); overflow: hidden; height: 12.8px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span><span data-i="8" style="color: rgb(97, 183, 58); overflow: hidden; height: 14.4px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span><span data-i="9" style="color: rgb(105, 192, 68); overflow: hidden; height: 16px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span><span data-i="10" style="color: rgb(113, 201, 78); overflow: hidden; height: 17.6px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span><span data-i="11" style="color: rgb(121, 210, 88); overflow: hidden; height: 19.2px;">Lorem ipsum dolor sit amet, tincidunt ut laoreet dolore magna aliquam erat volutpat.</span>

在此处输入图片描述

再一次,但是!

如果你想让这些渐变效果移动并创建一个动画呢?

嗯,还有另一种解决方案。你一定要检查#0甚至#1方法,这将导致基于光标位置的渐变开始!(听起来很酷xD)

在此处输入图片描述

这就是我们如何在文本上创建渐变(线性或径向)。如果你喜欢这个想法或想了解更多,你应该检查提供的链接。


也许这不是最好的选择,也许不是最好的表现方式,但它将开辟一些空间来创造令人兴奋和愉快的动画,以激励其他人寻求更好的解决方案。

它将允许您在文本上使用渐变样式,甚至IE8也支持!

在这里你可以找到一个工作现场演示,原始存储库是也在GitHub上,开源,并准备获得一些更新(: D)

这是我第一次(是的,5年后,你没听错)在互联网上的任何地方提到这个存储库,我对此感到兴奋!


[更新-2019年8月:] Github删除了该存储库的github页面演示,因为我来自伊朗!只有源代码可用这里 tho…

输入图片描述

这是一个仅用于全文的CSS解决方案,而不仅仅是一个字符元素。

div {position: relative;top: 2em;height: 2em;text-transform: full-width;}
div:before,div:after {content: attr(data-content);position: absolute;top: 0;right: 0;bottom: 0;left: 0;}
div:after {color: red;/* mask for a single character. By repeating this mask, all the string becomes masked */-webkit-mask-image: linear-gradient(to right, transparent 0, transparent .5em, white .5em, white 1em);-webkit-mask-repeat: repeat-x;  /* repeat the mask towards the right */-webkit-mask-size: 1em;         /* relative width of a single character */    
/* non-vendor mask settings */mask-image: linear-gradient(to right, transparent 0, transparent .5em, white .5em, white 1em);mask-repeat: repeat-x;mask-size: 1em;}

/* demo purposes */input[name="fontSize"]:first-of-type:checked ~ div {font-size: 1em;}
input[name="fontSize"]:first-of-type + input:checked ~ div {font-size: 2em;}
input[name="fontSize"]:first-of-type + input + input:checked ~ div {font-size: 3em;}
Font-size:<input type="radio" name="fontSize" value="1em"><input type="radio" name="fontSize" value="2em" checked><input type="radio" name="fontSize" value="3em">
<div data-content="A CSS only solution..."></div><div data-content="Try it on Firefox!"></div>

这个想法是为每个字符应用一个水平的CSS掩码,隐藏它的前半部分[0-0.5em]并显示后半部分[0.5em-1em]。

掩码的宽度为mask-size: 1em以匹配字符串中第一个字符的宽度。通过使用mask-repeat: repeat-x,将相同的掩码应用于第二个、第三个字符等。

我以为使用字体monospace可以解决使用同宽字母的问题,但我错了。相反,我通过使用#0解决了它,不幸的是只有Firefox支持,我相信。

相对单元em的使用允许设计根据font-size向上/向下扩展。

适用于所有浏览器的Vanilla JavaScript解决方案

如果Firefox不是一个选项,请使用此脚本进行救援。

它的工作原理是为每个字符插入一个子字符span。在每个跨度内,从[0%-50%]和[50%-100%]字母宽度(即跨度元素的宽度)放置一个不重复的CSS掩码。

这样我们就不再有使用同宽字符的限制。

constdataElement = document.getElementById("data"),content = dataElement.textContent,zoom = function (fontSize) {dataElement.style['font-size'] = fontSize + 'em';};
while (dataElement.firstChild) {dataElement.firstChild.remove()}for(var i = 0; i < content.length; ++i) {constspanElem = document.createElement('span'),ch = content[i];spanElem.setAttribute('data-ch', ch);spanElem.appendChild(document.createTextNode(ch === ' ' ? '\u00A0' : ch));data.appendChild(spanElem);}
#data {position: relative;top: 2em;height: 2em;font-size: 2em;}
#data span {display: inline-block;position: relative;color: transparent;}
#data span:before,#data span:after {content: attr(data-ch);display: inline-block;position: absolute;top: 0;right: 0;bottom: 0;left: 0;text-align: center;color: initial;}
#data span:after {color: red;-webkit-mask-image: linear-gradient(to right, transparent 0, transparent 50%, white 50%, white 100%);mask-image: linear-gradient(to right, transparent 0, transparent 50%, white 50%, white 100%);}
Font-size:<input type="range" min=1 max=4 step=0.05 value=2 oninput="zoom(this.value)" onchange="zoom(this.value)">
<div id="data">A Fallback Solution...For all browsers</div>

所有的解决方案都通过拆分字母并将它们包装在<span>中来工作。我们不必在两种情况下拆分字母:

  • 如果字体是等宽字体。
  • 如果使用垂直布局。

div {font-size: 80px;font-weight: bolder;color: transparent;padding: 0;margin: 0;background: linear-gradient(90deg, rgb(34, 67, 143) 0% 50%, #409FBF 50%);background-clip: text;-webkit-background-clip: text;}
.one {font-family: 'Nova Mono';background-repeat: repeat-x;background-size: 45px;}
.two {font-family: 'Gideon Roman';writing-mode: vertical-lr;text-orientation: upright;letter-spacing: -35px;height: 500px;}
<!-- get the fonts --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Nova+Mono&display=swap" rel="stylesheet"><link href="https://fonts.googleapis.com/css2?family=Gideon+Roman&display=swap" rel="stylesheet">

<div id='one' class="one">X-RAY Winter</div><div class="two">Minty</div>

预期输出,如果字体不可用:

输入图片描述

我知道使用背景剪辑和渐变已经在其他答案中得到了证明,只是把你不必拆分字母的情况。