I am creating a website where a black div is in the center and an image in the center rotates when I hover over it. The problem is that though I placed the image in the div, it comes out of the div. How to fix it? This is my HTML code:
const image = document.getElementById("pic");
image.classList.add("rotate");
const clone = image.cloneNode(true);
clone.classList.add("rotate-negative");
clone.classList.add("top-image");
clone.classList.add("shadow-lg");
document.getElementById("container").appendChild(clone);
img {
transition: 0.5s;
max-height: 600px;
}
.rotate{
transform: rotate(15deg);
position: absolute;
top: 0;
left: 0;
}
.rotate-negative{
transform: rotate(-5deg);
position: absolute;
top: 0;
left: 0;
}
.top-image:hover{
transform: rotate(0deg);
transition: 0.5s;
max-height: 620px;
}
#container{
margin-left: auto;
margin-right: auto;
height: 500px;
width: 30%;
background-color: black;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
<div id="container">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcToJI-yx2dCcsVf3fYDDRF908iRO_dlTsL9H32iWWIkT_1dYuimsdBUZKTIZgYC61z6Vik&usqp=CAU" id="pic">
</div>
I want the images to be placed inside the div. Though, I don’t want to remove the "position" property from the CSS because it will ruin the design of the images in the center. Without removing the ‘position’ property, what can I do to force the images to remain inside the div?
3
Answers
Here is the working example:
Simply adding
position: relative
to your#container
selector will do it. That keeps the positioning of the child elements relative to this elementIf needed you could also add
overflow:hidden
to cut off anything that "overflows" outside of this element. I’m not sure if you want/need the second one though, so remove that if you don’t need it.I made some minor changes on your CSS. This should work just fine.