Home > database >  Change the DIV background-color permanently
Change the DIV background-color permanently

Time:09-22

How can I change the background color of a div tag permanently once it is clicked. Tried the following code :

div {
 min-height: 50px;
 background-color: yellow;
 border-radius: 4px 4px 0 0;
 padding: 10px;
 display: flex;
 align-items: center;

   &:active {
      background-color: red;
    }
 }

But with this the background color is restored to previous one after the click is released. Is there a way to do this with SCSS and html alone?

<div class="div">
  <p>Hello</p>
</div>

CodePudding user response:

If you want pure CSS/SCSS approach, you can do it using transition delay. First of all you set transition of 0s, and a delay of some higher value (like 100000s). Now when you active the element, change the transition to 0s without delay so that it changes it's color immediately, now since there is a huge delay it becomes almost permanent. (but after the delay time that you set is over, it would become back to it's initial state)

div {
 min-height: 50px;
 background-color: yellow;
 border-radius: 4px 4px 0 0;
 padding: 10px;
 display: flex;
 align-items: center;
 transition: background-color 0s 100000s;

   &:active {
      background-color: red;
      transition: background-color 0s;
    }
 }

div {
 min-height: 50px;
 background-color: yellow;
 border-radius: 4px 4px 0 0;
 padding: 10px;
 display: flex;
 align-items: center;
 transition: background-color 0s 100000s;
 }
 
 div:active {
    background-color: red;
    transition: background-color 0s;
 }
<div></div>

CodePudding user response:

HTML

 <div class="div" id="myDiv">
   <p>Hello</p>
 </div>

CSS

 div {
  min-height: 50px;
  background-color: yellow;
  border-radius: 4px 4px 0 0;
  padding: 10px;
  display: flex;
  align-items: center;
  }

JS

 let myDiv=document.getElementById("myDiv");

 myDiv.addEventListener('click',()=>{
   myDiv.style.background='red';
 })

  • Related