I'm trying to build a photo galley so that when you press a photo, it overlays the website, and the background turns grey, and there is an animation of the photo turning big.
This is the animation:
@keyframes img {
0% {
position: static;
}
100% {
position: fixed;
top: 10%;
left: 10%;
margin: auto;
width: 80%;
height: 80%;
}
}
The problem is that css don't animate changing the position from static to fixed. Is there a solution to this problem?
Tried calculating the location of the image. Did not work
In CSS-animations, position is not a Animatable Property.
If you want to see the list CSS-animations properties: here
However you can use JavaScript get the same effect.
Edit : Example HTML
<div class="img-container">
<div class="opened"></div>
<img
class="img"
src="https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
<img class="img"
src=https://images.pexels.com/photos/406014/pexels-photo-406014.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt="" />
<img
class="img"
src="https://images.pexels.com/photos/2023384/pexels-photo-2023384.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
<img
class="img"
src="https://images.pexels.com/photos/1851164/pexels-photo-1851164.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
alt=""
/>
</div>
CSS
.img-container {
width: 100%;
height: 100vh;
display: flex;
overflow-x: hidden;
flex-wrap: wrap;
justify-content: center;
gap: 5%;
}
.img-container img {
width: 35vw;
height: 40vh;
object-fit: cover;
cursor: pointer;
}
.img-container .opened {
position: fixed;
overflow: scroll;
overflow-x: hidden;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 5%;
display: none;
}
.img-container .opened.active {
z-index: 100;
display: inline;
background-color: rgba(0, 0, 0, 0.424);
}
.img-container .opened img {
width: 100%;
height: 100%;
}
JS
const imgContainer = document.querySelector(".img-container");
const imgs = document.querySelectorAll(".img");
const openedDiv = document.querySelector(".opened");
const toggleImg = (e) => {
// selecting the img inside opened div
let clickedImgSrc = e.target.src;
let imgElement = document.createElement("img");
imgElement.setAttribute("src", clickedImgSrc);
openedDiv.appendChild(imgElement);
openedDiv.classList.add("active");
};
const closeTheOpened = () => {
openedDiv.removeChild(openedDiv.firstChild);
openedDiv.classList.remove("active");
};
imgs.forEach((img) => img.addEventListener("click", toggleImg));
openedDiv.addEventListener("click", closeTheOpened);