Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 21, 2023 › #css #HowTo

How to change div content in CSS?

To change the content of a div element in CSS, you can use of the ::after pseudo-element and the content property. The example is given below.

<style>
#my-div::after {
  content: "New Text";
}
</style>
<div id="my-div">Old Text</div>

This will add the text "New Text" after the original content of the div.

You can also use the attr() function to retrieve an attribute of the element to use as the new content.

<style>
#my-div::after {
  content: attr(data-text);
}
</style>

<div id="my-div" data-text="New Text">Old Text</div>

This will change the content of the div to "New Text".

Note that changing the content of an element in CSS is purely visual and does not affect the actual content of the element in the DOM. If you want to change the actual content of the element, you need to use JavaScript.

  1. Add an icon after the content of a div element.
    <style>
    #my-div::after {
      content: url(https://app.3schools.in/logo.png);
      margin-left: 5px;
    }
    </style>
       
    <div id="my-div">Old Text</div>
  2. Add a label before the content of a div element.
       
      <style>
    #my-div::after {
      content: "Label: Computer";
      font-weight: bold;
    }
    </style>
    
    <div id="my-div">Old Text</div>
  3. Add a background image after the content of a div element.
    <style>
    #my-div::after {
      content: "";
      display: block;
      height: 20px;
      width: 20px;
      background-image: url(https://app.3schools.in/img/bg.png);
      background-size: contain;
      background-repeat: no-repeat;
    }
    </style>
    <div id="my-div">Old Text</div>
  4. Use the content property to display a counter.
    <style>
    .my-div{
      counter-increment: my-counter;
    }
    .my-div::after {
      content: counter(my-counter);
    }
    </style> 
    
    <div class="my-div">Old Text </div>
    <div class="my-div">Old Text </div>
save
listen
AI Answer
Write Your Answer
loading
back
View All