Home > Enterprise >  How to keep button fixed on a div while background- image of this can rotate. Using Javascript Only?
How to keep button fixed on a div while background- image of this can rotate. Using Javascript Only?

Time:11-18

I need a div where a background image will be set but there should be a button on bottom of image (content of same div).

When this button will be click then background image should be rotate not Button.

Is this possible using JavaScript Only?

this is code sample

function rotate() {
  document.getElementById("img_container").style.transform = "rotate(45deg)";
}
.container {
  position: relative;
  height: 400px;
  max-width: 400px;
  background: url("https://www.w3schools.com/howto/img_snow.jpg");
}

.container .btn {
  position: absolute;
  top: 90%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background-color: #555;
  color: white;
  font-size: 16px;
  padding: 12px 24px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
}

.container .btn:hover {
  background-color: black;
}
<div  id="img_container">
  <button  onClick="rotate()">Button</button>
</div>

CodePudding user response:

Try keeping the button div outside the container div. Since you have kept "btn" inside "container", the button is inheriting all the css of container. Keep the button independent.

CodePudding user response:

Wouldn't this work for you? Create the container where you would have a div with the background image and the rotate button. And then only rotate the div with the image.

function rotate() {
  document.getElementById("img_container").style.transform = "rotate(45deg)";
}
.container {
  position: relative;
  height: 400px;
  max-width: 400px;
  
}

#img_container {
 background: url("https://www.w3schools.com/howto/img_snow.jpg");
 width: 100%;
 height:100%;
}

.container .btn {
  position: absolute;
  top: 90%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  background-color: #555;
  color: white;
  font-size: 16px;
  padding: 12px 24px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  text-align: center;
}

.container .btn:hover {
  background-color: black;
}
  
<div >
  <div id="img_container"></div>
  <button  onClick="rotate()">Button</button>
</div>

  • Related