skip to Main Content
<label class="custom-label">arun</label> 

<style>
:root {--custom-text: "New Text"; /* Replace with your desired text */}

.custom-label::before {content: var(--custom-text);}

</style>

I have found that using before and after pseudo-elements, but I want to change the content (‘arun’) by using a CSS variable. Is it possible?

2

Answers


  1. Yes, it is possible to change the content of the <label> element (‘arun’) using a CSS variable. The code you provided already includes a CSS variable (--custom-text) that can be used to change the content dynamically.

    To change the content of the <label> element, you need to modify the value of the --custom-text CSS variable. Here’s how you can do it:

    HTML:

    <label class="custom-label">arun</label>
    

    CSS:

    :root {
      --custom-text: "New Text"; /* Replace with your desired text */
    }
    
    .custom-label::before {
      content: var(--custom-text);
    }
    

    To change the content, you can add some JavaScript to modify the CSS variable value:

    JavaScript:

    // Get the <label> element
    const customLabel = document.querySelector(".custom-label");
    
    // Function to change the content
    function changeContent(newContent) {
      // Set the value of the CSS variable to the new content
      document.documentElement.style.setProperty("--custom-text", `"${newContent}"`);
    }
    
    // Example usage
    changeContent("Hello, World!");
    

    In the example above, the changeContent function takes a string as input and updates the value of the --custom-text CSS variable accordingly. When you call this function with the desired content, it will change the content of the <label> element to the specified text.

    Remember to properly handle the user input or data if you are accepting content from users, as this method could be used for potential code injection or XSS attacks if not properly sanitized.

    Login or Signup to reply.
  2. Set font-size: 0 for the label, and reset it for the pseudo element. (You won’t be able to use a unit like em then, obviously, so if you need it to be somehow dynamic, you will have to make it work with rem then.)

    :root {--custom-text: "New Text"; /* Replace with your desired text */}
    
    .custom-label { font-size: 0; }
    .custom-label::before {font-size: 1rem; content: var(--custom-text);}
    <label class="custom-label">arun</label>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search