Switch the color of the final letter

Sample code snippet:

<p class="test">string</p>

Looking to dynamically change the color of the last letter, specifically the letter "g", using CSS only, without relying on JavaScript.

I am displaying the string character by character and need a solution that can be applied dynamically.

Answer №1

While many may doubt its feasibility, I am determined to prove them wrong.

Indeed, it is possible.

Admittedly, it may be a crude workaround, but it can be achieved.

To accomplish this, we will utilize two key CSS functionalities:

  • Firstly, CSS allows for the modification of text flow direction. While typically used for languages like Arabic or Hebrew, it can reverse the display order of any text, including English. For instance, to display the word "String" in reverse on an element, the markup would need to be "gnirtS".

  • Secondly, CSS includes the ::first-letter pseudo-element selector, which targets the initial letter in a text. (although there is no equivalent ::last-letter selector)

By combining the ::first-letter with the reversed text, we effectively highlight the first letter of "gnirtS" which visually appears as the last letter of "String".

div {
  float: left;
  unicode-bidi: bidi-override;
  direction: rtl;
}

div::first-letter {
  color: blue;
}
<div>gnirtS</div>

Indeed, this technique does work - a demonstration can be viewed in this working fiddle.

However, it must be acknowledged that this method is somewhat unconventional. Reversing text manually is not a practical solution, despite providing an answer to the query.

Answer №2

Combine the ::after pseudo-element with the attr() function to achieve the following:

p::after {
    content: attr(data-end) ;
    color: red ;
}
<p data-end="g">Strin</p>

p::after {
  content: attr(data-end) ;
  color: red ;
}
<p data-end="g">Strin</p>

Answer №3

One alternative approach is to utilize the ::after pseudo-element

.test::after{
    content: "g";
    color: yellow;
}
<p class="test">strin</p>

This method enables the color change of all characters, not just letters, unlike the method suggested by Spudley which utilizes ::first-letter. Refer to the specification for ::first-letter for further details. The ::first-letter only affects letters and ignores punctuation symbols.

Furthermore, if you wish to apply color to more than the last character, you can do the following:

.test::after{
     content: "ing";
     color: yellow;
}
<p class="test">str</p>

For additional insights on using ::after, visit this link.

Answer №4

If you want to avoid using javascript, you can follow this approach:

<p class="test">strin<span class="other-color">g</span></p>

Make sure to adjust for your particular fiddle link:

It seems contradictory that you mentioned not needing a javascript solution when your current code already includes it. However, in this scenario, you only need to make a few modifications. Edit line 10 from:

elem.text(elem.text() + contentArray[current++]);

to:

if ( current == contentArray.length-1 ) {
    elem.html(elem.html() + "<span style='color:red'>"+contentArray[current++]+"</span>");
} else {
    elem.html(elem.html() + contentArray[current++]);
}

Remember to utilize .html() instead of .text() now, as there is HTML content being inserted.

Check out the working fiddle here: http://jsfiddle.net/QTUsb/2/

Answer №5

To accomplish this effect without altering the HTML structure, you can utilize CSS alongside the ::after pseudo-element:

.custom-text {
  font-size: 16pt;
  position: relative;
}
.custom-text::after {
  bottom: 0;
  color: blue;
  content: 'x';
  position: absolute;
  transform: translate(-100%, 0);
}
<p class="custom-text">example text</p>

Answer №6

How can you achieve the effect of displaying each letter of a string individually? One approach is to iterate through the characters in the string (variable) and detect when you reach the last letter to apply a specific formatting, whether this is done on the server side or client side.

Referencing the code snippets included in another one of your inquiries...

If this is the behavior you are referring to, consider updating the .innerHTML of the element instead of utilizing element.text()

Based on the example in http://jsfiddle.net/SLKEn/, you could modify it to resemble the following:

if(current < contentArray.length) {
    elem.html(
            elem.html() +
              (current == contentArray.length-1 ?
               '<span class="lastchar">' + contentArray[current++] + '</span>' :
               contentArray[current++])
             );
        }

Additionally, include the CSS rule span.lastchar { color: red; }


Update: Check out the revised fiddle based on your previous question.

Answer №7

$(document).ready(function() {
  var str=$("span").text();
  strArr=str.split("");
  for(var key=0;key<strArr.length-1;key++) {
    if(key==strArr.length-1) {
      var newEle="<span id='lastElement'>"+strArr[key]+"</div>";
      strArr[key]=newEle;
    }
  }
  var newtext=strArr.join("");
  $("span").html(newtext);  
});
  
span#lastElement {
  color: red;
}

Answer №8

Unfortunately, I am unable to leave a comment on the answer thread, but I noticed a mistake in a solution provided by Marc_Alx that was otherwise excellent. The solution worked for me only after I added a semicolon after the content property... so it appears like content:"ing";

.test::after{
  content:"ing";
  color:yellow;
}
<p class="test">str</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for including preset text within a search bar?

My current issue is as follows: When the searchbox is focused, it appears like this: -------------------- -------------------- Upon exiting the searchbox, a string will automatically be added to it: -------------------- Search -------------------- I a ...

Adjusting Classes in JavaScript with jQuery

I need to create a feature that changes the state of a button from active to inactive based on user input, using Bootstrap. Ultimately, I am working towards finding an intuitive way to validate form input so that the submit button can be pressed for PHP pr ...

Steps for adding a background image to a div element

I am struggling to place my background behind the jumbotron div, but no matter what I do, it always ends up appearing below the image instead of on top of it. Can someone please guide me on how to resolve this issue? Note: I have a specific requirement wh ...

Various Ways to Add Hyperlinks in HTML Using CSS Styles

Does anyone know how I can link multiple HTML files to one hyperlink, where only one file opens randomly when clicked? I am currently using . Your assistance would be greatly appreciated! I've tried searching online for a solution, but haven't ...

Is it possible to reference the same PHP file in multiple locations?

Currently, I am working on a web development project where I have created a header.html file to store the common header for all my webpages. This header file is located in the parent directory. Within my header.html file, I have included references to bot ...

Is it possible to modify the appearance of the element that was just clicked on?

Hello everyone, I'm currently working on a form with different inputs, all with the same class: <input type="text" name="username" class="field" /> <input type="text" name="email" class="field" /> I'm trying to figure out how to ch ...

What is the best method to "deactivate" a radio button while ensuring that a screen reader can still read the text and notify the user that it is inactive?

My current situation involves needing to deactivate certain radio buttons, while still having the option to reactivate them later. When I use the disabled attribute, screen readers will overlook this field and miss key information. I am seeking an accessi ...

What could be the reason for the page scrolling upwards when clicking on href="#"?

I am encountering an issue with a hyperlink <a href="#" id="someID">Link</a> that is located further down the page. This link is used to trigger an Ajax request, but whenever it is clicked, the page automatically scrolls back to the top. I have ...

Expanding list item with jQuery

I am facing an issue with the dropdown functionality of my <li> elements. The problem occurs when clicking on the 4th option, as the expander appears on top instead of dropping down beneath the list item. If you check out this jsFiddle, you can see ...

The scrolling feature within individual div elements seems to be malfunctioning in Ionic 2

In my current project using Ionic 2, I am faced with the task of designing a screen that contains two distinct grid views. The first grid view needs to occupy 40% of the height, allowing for scrolling within that specified area. On the other hand, the se ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

Using Vanilla JavaScript to Disable a Specific Key Combination on a Web Page

On a completely random English-Wikipedia editing page, there exists a way to add content (for example, "test") and save it using the existing key combination of Alt+Shift+S. My goal is to specifically prevent this action without removing the save button b ...

Obtaining values from alternating nodes in a SQL query

Can anyone help with extracting values of odd and even nodes in SQL from this XML example? declare @htmlXML xml = N'<div class="screen_specs_container "><div class="left_specs_container">Compatibility:</div><div class="right_spe ...

Displaying an automatic row using jQuery in real-time

I am struggling with displaying a default table row using jQuery. Specifically, I am using the remove() method to delete a table row, but I am unsure how to show a default row if there are no entries to display. Below is the code snippet in question: fu ...

Modify the class of rows in table 2 once a particular value of a radio button in table 1 has been selected

One issue I am facing is related to two tables with radio buttons. Each table highlights the corresponding row when a radio button is checked, working independently. However, I need a specific value from table 1 to un-highlight any previously checked rows ...

Employing delegate for switching roles between classes

I'm having trouble using the jQuery delegate function to toggle classes. What I want to achieve is toggling the class of <li class="unselected-values"> to <li class="<li class="unselected-values"> when the client clicks on the label ...

Having Difficulty Formatting HTML Input in Next.js

I'm encountering difficulties when trying to style HTML form elements in Next.js. I've been unsuccessful in applying CSS using a simple class name from the imported stylesheet, but have managed to achieve some success with inline styling by using ...

Unable to display image on HTML page in Sails JS

In my current project, I am utilizing Sails Js and Mongo DB for development. When a user uploads an image and content for a blog post, I store it in the images folder and save the file destination along with the content to MongoDB. My goal is to display bo ...

I'm confused as to why only one of my HTML pages is accepting my CSS styling - not sure what's going on

I am facing an issue where the CSS styles are only being applied to one of the HTML pages I created. Despite checking my code multiple times, everything seems to be correct. All the necessary files are saved on my laptop in the same folder for the website. ...

Concealing content to prevent it from being accessed through HTML and JavaScript inspection techniques

I created a website with a simple guessing game where users can win if they enter the right code. My approach involves using JavaScript: <script> function z() { var b = document.getElementById('idea'); var a = document.g ...