Home > Web Front-end > JS Tutorial > body text

How to Style Half of a Character with Pure CSS?

DDD
Release: 2024-10-30 01:52:02
Original
704 people have browsed it

How to Style Half of a Character with Pure CSS?

How to Apply CSS to Half of a Character

Background:

You're seeking a solution to style one half of a character, making it transparent in this instance. Previous attempts using methods like styling part of a character with CSS or JavaScript have been unsuccessful. An image-based solution is undesirable due to the dynamic nature of the text.

Solution: Half-Style

Introducing Half-Style:

Half-Style is a solution that offers pure CSS styling for a single character or JavaScript-based automation across multiple characters. It maintains accessibility for screen readers.

Part 1: Basic Solution (Single Character)

Simply apply the ".halfStyle" class to the character you wish to style, along with a "data-content" attribute containing the character's value.

Example:

<code class="html"><span class="halfStyle" data-content="X">X</span></code>
Copy after login

Part 2: Automated Solution

For multiple characters or dynamic text, use the ".textToHalfStyle" class on the parent element and apply JavaScript to generate the styled elements.

Code Snippet:

<code class="javascript">// jQuery for automated mode
$('.textToHalfStyle').each(function(idx, el) {
  var text = $(el).text(),
      chars = text.split(''),
      output = '';

  for (var i = 0; i < chars.length; i++) {
    output += '<span aria-hidden="true" class="halfStyle" data-content="' + chars[i] + '">' + chars[i] + '</span>';
  }

  $(el).append(output);
});</code>
Copy after login

CSS:

<code class="css">.halfStyle {
  font-size: 80px;
  color: black;
  white-space: pre;
}

.halfStyle:before {
  display: block;
  width: 50%;
  content: attr(data-content);
  color: #f00;
}</code>
Copy after login

Live Demo: https://jsfiddle.net/arbel/pd9yB/1694/

Github Plugin: https://github.com/arbel/half-style

The above is the detailed content of How to Style Half of a Character with Pure CSS?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!