Is it possible to apply CSS to half of a character

2019-01-01 01:17发布

What I am looking for:

A way to style one HALF of a character. (In this case, half the letter being transparent)

What I have currently searched for and tried (With no luck):

  • Methods for styling half of a character/letter
  • Styling part of a character with CSS or JavaScript
  • Apply CSS to 50% of a character

Below is an example of what I am trying to obtain.

x

Does a CSS or JavaScript solution exist for this, or am I going to have to resort to images? I would prefer not to go the image route as this text will end up being generated dynamically.


UPDATE:

Since many have asked why I would ever want to style half of a character, this is why. My city had recently spent $250,000 to define a new "brand" for itself. This logo is what they came up with. Many people have complained about the simplicity and lack of creativity and continue to do so. My goal was to come up with this website as a joke. Type in 'Halifax' and you will see what I mean.

19条回答
笑指拈花
2楼-- · 2019-01-01 01:35

Just for the record in history!

I've come up with a solution for my own work from 5-6 years ago, which is Gradext ( pure javascript and pure css, no dependency ) .

The technical explanation is you can create an element like this:

<span>A</span>

now if you want to make a gradient on text, you need to create some multiple layers, each individually specifically colored and the spectrum created will illustrate the gradient effect.

for example look at this is the word lorem inside of a <span> and will cause a horizontal gradient effect ( check the examples ):

 <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>

and you can continue doing this pattern for a long time and long paragraph as well.

enter image description here

But!

What if you want to create a vertical gradient effect on texts?

Then there's another solution which could be helpful. I will describe in details.

Assuming our first <span> again. but the content shouldn't be the letters individually; the content should be the whole text, and now we're going to copy the same ‍‍<span> again and again ( count of spans will define the quality of your gradient, more span, better result, but poor performance ). have a look at this:

<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>

enter image description here

Again, But!

what if you want to make these gradient effects to move and create an animation out of it?

well, there's another solution for it too. You should definitely check animation: true or even .hoverable() method which will lead to a gradient to starting based on cursor! ( sounds cool xD )

enter image description here

this is simply how we're creating gradients ( linear or radial ) on texts. If you liked the idea or want to know more about it, you should check the links provided.


Maybe this is not the best option, maybe not the best performant way to do this, but it will open up some space to create exciting and delightful animations to inspire some other people for a better solution.

It will allow you to use gradient style on texts, which is supported by even IE8!

Here you can find a working live demo and the original repository is here on GitHub as well, open source and ready to get some updates ( :D )

This is my first time ( yeah, after 5 years, you've heard it right ) to mention this repository anywhere on the Internet, and I'm excited about that!

查看更多
怪性笑人.
3楼-- · 2019-01-01 01:37

Example


JSFiddle DEMO

We'll do it using just CSS pseudo selectors!

This technique will work with dynamically generated content and different font sizes and widths.

HTML:

<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;
}

To wrap the dynamically generated string, you could use a function like this:

// Wrap each letter in a span tag and return an HTML string
// that can be used to replace the original text
function 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 text
window.onload = function() {
    var el  = document.querySelector('.split-color'),
        txt = el.innerHTML;

    el.innerHTML = wrapString(txt);
}
查看更多
冷夜・残月
4楼-- · 2019-01-01 01:37

This can be achieved with just CSS :before selector and 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>

>> See on jsFiddle

查看更多
伤终究还是伤i
5楼-- · 2019-01-01 01:38

enter image description here


I've just finished developing the plugin and it is available for everyone to use! Hope you will enjoy it.

View Project on GitHub - View Project Website. (so you can see all the split styles)

Usage

First of all, make sure you have the jQuery library is included. The best way to get the latest jQuery version is to update your head tag with:

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

After downloading the files, make sure you include them in your project:

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

Markup

All you have to do is to asign the class splitchar , followed by the desired style to the element wrapping your text. e.g

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

After all this is done, just make sure you call the jQuery function in your document ready file like this:

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

Customizing

In order to make the text look exactly as you want it to, all you have to do is apply your design like this:

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


That's it! Now you have the Splitchar plugin all set. More info about it at http://razvanbalosin.com/Splitchar.js/.

查看更多
不流泪的眼
6楼-- · 2019-01-01 01:39

Here an ugly implementation in canvas. I tried this solution, but the results are worse than I expected, so here it is anyway.

Canvas example

        $("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>

查看更多
柔情千种
7楼-- · 2019-01-01 01:40

You can use below code. Here in this example I have used h1 tag and added an attribute data-title-text="Display Text" which will appear with different color text on h1 tag text element, which gives effect halfcolored text as shown in below example

enter image description here

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>

查看更多
登录 后发表回答