How to replace text with CSS? - GeeksforGeeks (2024)

Skip to content

How to replace text with CSS? - GeeksforGeeks (1)

Last Updated : 15 Sep, 2024

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

Replacing text on a webpage is typically done on the server side, but there are situations where you might need to do this directly in CSS. This can be useful when you don’t have server access or are working within certain restrictions. CSS offers a couple of methods to replace text, which we’ll explore here.

Table of Content

  • Using :after Pseudo-element

Using :after Pseudo-element

The :after pseudo-element allows you to insert content after the selected element. You can use this technique to replace text by hiding the original text and placing new text in its place.

Steps:

  • Wrap the Text: Assign a class to the text you want to replace.
<p class="toBeReplaced">Old Text</p>
  • The text “Old Text” needs to be hidden first and a new text has to be positioned exactly where the old text was. To do so, we change the visibility of this text using CSS to hidden first.
.toBeReplaced { visibility: hidden; position: relative;}
  • Then we add a new text at the exact same position, using the pseudo elements and corresponding explicit positioning.
.toBeReplaced:after { visibility: visible; position: absolute; top: 0; left: 0; content: "This text replaces the original.";}

Note: after is the pseudo element in use here. We use the visibility modifier once again to show the new text. The content attribute contains the new text.

Example: Implementation to replace text using :after Pseudo-element

html
<!DOCTYPE html><html lang="en"><head> <title> Using :after Pseudo-element </title> <style> .toBeReplaced { visibility: hidden; position: relative; } .toBeReplaced:after { visibility: visible; position: absolute; top: 0; left: 0; content: "This text replaces the original."; } </style></head><body> <p class="toBeReplaced">Old Text</p></body></html>

Output:

How to replace text with CSS? - GeeksforGeeks (3)

Using Pseudo-elements & CSS Visibility

Another approach involves hiding the original text using a <span> element and displaying new text with the :after pseudo-element.

Steps:

  • Wrap the original text within a <span> element, serving as a child of the <p> element with the class .toBeReplaced.
  • Apply display: none; to the <span> element, ensuring the original text is hidden from view.
  • Utilize the :after pseudo-element on the .toBeReplaced class to insert content that replaces the hidden text.
.toBeReplaced span { display: none;}.toBeReplaced:after { content: "This text replaces the original.";}

Example: Implementation to replace text using aabove approach.

html
<!DOCTYPE html><html><head> <title> Using Pseudo-elements & CSS Visibility </title> <style> .toBeReplaced span { display: none; } .toBeReplaced:after { content: "This text replaces the original."; } </style></head><body> <p class="toBeReplaced"><span>Old Text</span></p></body></html>

Output:

How to replace text with CSS? - GeeksforGeeks (4)

By using these CSS techniques, you can effectively replace text on a webpage without needing to modify the server-side code. Whether you choose to utilize the :after pseudo-element or combine pseudo-elements with CSS visibility, these methods offer flexibility and control over how text is displayed.



How to replace text with CSS? - GeeksforGeeks (5)

Improve

Please Login to comment...

Similar Reads

How to replace a text in a string with another text using PHP ?

A string is a sequence of one or more characters. A string is composed of characters, each of which can be replaced easily in the script. A large number of in-built PHP methods can be used to perform string replacements. Table of Content Using str_replace() method - The str_replace() Using str_ireplace() method Using preg_replace()Using substr_repl

4 min read

How to create long shadow of text without using text-shadow in HTML and CSS ?

Shadows are really a nice way to give depth and 3-D look to any text. Generally, we use text-shadow to give shadow to the text but this shadow is short and to create long shadow (shadow in which text is visible like that of reflection) we have to use before selector and skew function. Approach: The approach is to use a skew to create tilted text fi

2 min read

Text Animation with changing the color of the text using HTML and CSS

Text animation is the creation of beautiful and colorful letters, words, and paragraphs with a decorative movable effect. The movement can be seen in some fashion within the area or across the screen following some regular pattern. The @keyframes in CSS allows defining a series of animations at specific points during an animation sequence. In this

2 min read

How to Style the Text using text-decoration Property in CSS ?

The text-decoration property in CSS is used to style the decoration of text, such as underlining, overlining, line-through, and blink effects. It is a versatile property that can enhance the visual appearance of text. Syntax/* Example of using the text-decoration property */ .element { text-decoration: [value]; }The text-decoration Property ValuesT

1 min read

How to replace text after a nested tag in jQuery ?

In this article, we will see how to replace text after a nested tag using jQuery. There is one main approach that can be followed. Approach: We use the click(), contents() and filter() methods and this, nodeType and nodeValue properties. There is one division element with an id of outer-tag with a span tag with a class of nested-tag nested within i

2 min read

How to select all text in HTML text input when clicked using JavaScript?

This example shows how to select entire input in a single click using javaScript. Syntax: &lt;input onClick="this.select();" &gt; or document.getElementById("ID").select(); Example-1: Using "this.select()". &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Select all text in HTML text input when clicked &lt;/title&gt; &lt;/head&gt; &lt;

1 min read

How to get text inside Text component onPress in ReactJS ?

In this article, we will learn "How to get the text inside Text component onPress in ReactJS?". Problem Statement: Sometimes in an application, it is required to get the text inside certain components, in order to reuse the components again &amp; again just by changing the text value. Approach: We will set the property inside the component's tag to

4 min read

3 min read

How to embed text and text boxes in New Google Sites?

Embedding text and text boxes in New Google Sites is essential for creating a well-organized and visually appealing website. Text is a primary medium for conveying information, and properly formatted text boxes can enhance readability and user engagement. According to a study by the Nielsen Norman Group, users often skim web pages, focusing on head

4 min read

How to Create a Text input with helper text in react-native?

React native is a framework developed by Facebook for creating native-style apps for iOS &amp; Android under one common language, JavaScript. Initially, Facebook only developed React Native to support iOS. However, with its recent support of the Android operating system, the library can now render mobile UI's for both platforms. Prerequisites: Basi

3 min read

How to place cursor position at end of text in text input field using JavaScript ?

When working with forms or interactive elements in JavaScript, you might need to control the position of the cursor within a text input field. Specifically, you might want to place the cursor at the end of the current text, allowing users to easily continue typing without disrupting the existing content. In this article, we’ll see how to do this wi

3 min read

How to make div with left aligned text and right aligned icon using CSS ?

In this article, we will learn to create an HTML div that has left-aligned text and a right-aligned icon. Sometimes, we need to align the text to the left side &amp; if there is an image or icon used then align it to the right side. For this, we can use the display property by setting the value as a flex property that is used to display an element

3 min read

How to use text overflow property in CSS ?

In this article, we will see how to set text overflow property in CSS. The text-overflow property is used to specify that some text has overflown and hidden from view from the user. The text-overflow property only affects content that is overflowing a block container element. Syntax: text-overflow: clip| ellipsis Property Value: clip: Text is clipp

2 min read

How to disable text selection highlighting using CSS?

Making text unselectable is an easy task. All we have to do is to disable the selectivity of the text on our webpage for all the browsers that the webpage is likely to be loaded on. There are some settings/commands used in CSS which are used for enabling/disabling functionalities on specific browsers. Like to disable a certain functionality on our

1 min read

CSS | Text Effects

CSS is the mechanism to adding style in the various web documents. Text Effects allows us to apply different types of effect on text used in an HTML document. Below are some of the properties in CSS that can be used to add effects to text: text-overflow word-wrap word-break writing-mode Let's learn about each of these in details: Text-Overflow: The

4 min read

How to give text or an image transparent background using CSS ?

In this article, we will know to make the text or image a transparent background using the CSS &amp; will see its implementation through the example. The opacity property is used to set image or text transparent using CSS. The opacity attribute is used to adjust the transparency of text or pictures. The value of opacity lies between 0.0 to 1.0 wher

2 min read

Set the limit of text length to N lines using CSS

It is possible to limit the text length to [Tex]N[/Tex] lines using CSS. This is known as line clamping or multiple line truncating. There can be two possible cases: Truncating text after 1 line: If you need to truncate text after 1 line then the text-overflow property of CSS can be used. It creates ellipses and gracefully cut off words. div{ white

4 min read

How to make text input non-editable using CSS?

The read-only attribute in HTML is used to create a text input non-editable. But in case of CSS, the pointer-events property is used to stop the pointer events. Syntax: pointer-events: none; Example 1: This example shows two input text, in which one is non-editable. &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Disable Text Input fi

1 min read

How to select text input fields using CSS selector ?

CSS attribute selector is used to target input text fields. The input text fields of type 'text' can be targeted by using input[type=text]. Note: It is specified that the default attribute values may not always be selectable with attribute selectors, one could try to cover other cases of markup for which text inputs are rendered. input:not([type]):

2 min read

Neon Text Display Using HTML &amp; CSS

In this article, you will learn to create a neon text display using HTML &amp; CSS. The neon text display is the simplest yet one of the most striking effects used to give cool design to your texts on your web pages. In the neon display, the color of the text glows continuously which you can control by animation time. The text gets a glowing effect

3 min read

CSS | text-orientation Property

The text-orientation property in CSS is used to set the orientation of the character in a line. This property is useful in vertical scriptings, like creating vertical table headers, defining the row's names, etc. Syntax: text-orientation: mixed|upright|sideways; Attribute: mixed: This value is used to rotate the character of text into 90 degree clo

2 min read

CSS | text-decoration-skip-ink Property

The text-decoration-skip-ink property is used to specify how the underlines and overlines are rendered when they pass through the characters or glyphs. Syntax: text-decoration-skip-ink: auto | none Property Values: auto: This value is used to specify to skip the underlines and overlines that pass through a character. It is the default value.none: T

2 min read

Differences between HTML &lt;center&gt; Tag and CSS "text-align: center;" Property

If you are designing a simple web page, then not much difference is noticeable, but it is very necessary to understand the basic differences between these two. Since we are only concerned with the text, these elements do not have separate meanings.HTML &lt;center&gt; tag: The &lt;center&gt; tag in HTML is used to set to align of text into the cente

3 min read

How to Create a Cutout Text using HTML and CSS ?

Cutout text is used as a background header of the webpage. The cutout text creates an attractive look on the webpage. To create a cutout text we will use only HTML and CSS. We display the cutout text and then we make the text blending of an element’s background with the element’s parent. The CSS mix-blend-mode property is required to do that. Divid

3 min read

How to Shift Inline Elements When Text Bold on Hover using CSS ?

When we will use a:hover pseudo-class to add a bold effect to the inline elements then we observe that whenever we hover over elements with the mouse, the elements to the right side of the mouse gets shifted to the right. This is not a good user experience thus needs to be removed. We can use the letter-spacing CSS property to fix this issue and ma

2 min read

How to use text as background using CSS ?

There are some website designs that require using text as the background. This can be easily achieved with CSS by using the following methods. Using absolutely positioned element inside relatively positioned element: The absolutely positioned element inside a relative positioned element with absolute element having lower z-index value gives text ap

2 min read

How to Set the Gap Between Text and Underlining using CSS ?

Introduction: CSS is used to make the website visually more appealing and more readable. It can be used to format the text on the website in various ways like color, font-size, font-family, etc. In this article, we are going to see how in the case of underlined text, increase the gap between text and underline.Approach: The trick that we are going

1 min read

How to change the color of selected text using CSS ?

The colour of selected text can be easily changed by using the CSS | ::selection Selector. In the below code, we have used CSS ::selection on &lt;h1&gt; and &lt;p&gt; element and set its colour as yellow with green background. Below example implements the above approach: Example: &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt;

1 min read

How to Create Liquid Filling Effect on Text using HTML and CSS ?

The liquid fill text animation can be done using CSS | ::before selector. We will use key frames to set height for each frame of animation. Please make sure you know about both CSS | ::before selector and CSS | @keyframes Rule before try this code.The basic styling of the text can be done differently that totally depends on you how you want your te

3 min read

How to Create Embossed Text Effect using CSS ?

The embossed text effect can be easily generated using HTML and CSS. We will use the CSS text-shadow property to get the desired output. HTML Code: In this section, we will create a basic structure of the body that holds text or heading. &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot; dir=&quot;ltr&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;u

2 min read

Article Tags :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

How to replace text with CSS? - GeeksforGeeks (6)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

How to replace text with CSS? - GeeksforGeeks (2024)
Top Articles
Cashier's Check: Definition, Benefits, and Alternative Options
Cryptosporidium Pathogenicity and Virulence
Navicent Human Resources Phone Number
Menards Thermal Fuse
Golden Abyss - Chapter 5 - Lunar_Angel
Patreon, reimagined — a better future for creators and fans
Mrh Forum
Doublelist Paducah Ky
Wild Smile Stapleton
Find your energy supplier
Tripadvisor Near Me
Conan Exiles Thrall Master Build: Best Attributes, Armor, Skills, More
Craigslist Blackshear Ga
Nashville Predators Wiki
Samantha Lyne Wikipedia
Wal-Mart 140 Supercenter Products
Water Days For Modesto Ca
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Samantha Aufderheide
Japanese Mushrooms: 10 Popular Varieties and Simple Recipes - Japan Travel Guide MATCHA
Toothio Login
Walmart Pharmacy Near Me Open
Gilchrist Verband - Lumedis - Ihre Schulterspezialisten
Workshops - Canadian Dam Association (CDA-ACB)
Dashboard Unt
Dexter Gomovies
Phoenixdabarbie
Stephanie Bowe Downey Ca
Duke University Transcript Request
Florence Y'alls Standings
Pdx Weather Noaa
100 Million Naira In Dollars
Hypixel Skyblock Dyes
Yoshidakins
Green Bay Crime Reports Police Fire And Rescue
Rocketpult Infinite Fuel
拿到绿卡后一亩三分地
Craigslist Georgia Homes For Sale By Owner
Oxford Alabama Craigslist
Postgraduate | Student Recruitment
manhattan cars & trucks - by owner - craigslist
Umd Men's Basketball Duluth
Lamp Repair Kansas City Mo
Rage Of Harrogath Bugged
What Is The Optavia Diet—And How Does It Work?
Cvs Coit And Alpha
Uno Grade Scale
Coleman Funeral Home Olive Branch Ms Obituaries
Southern Blotting: Principle, Steps, Applications | Microbe Online
Latest Posts
Article information

Author: Carmelo Roob

Last Updated:

Views: 6218

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Carmelo Roob

Birthday: 1995-01-09

Address: Apt. 915 481 Sipes Cliff, New Gonzalobury, CO 80176

Phone: +6773780339780

Job: Sales Executive

Hobby: Gaming, Jogging, Rugby, Video gaming, Handball, Ice skating, Web surfing

Introduction: My name is Carmelo Roob, I am a modern, handsome, delightful, comfortable, attractive, vast, good person who loves writing and wants to share my knowledge and understanding with you.