Home > front end >  CSS Transition Over More Than One Image
CSS Transition Over More Than One Image

Time:03-08

I am trying to create a transition that moves a white div on top of an image. I can do that with ONE image currently, however, I would like to be able to do this with two or more images…

I think the issue has something to do with the position property here, but I am not sure what the actual solution would be.

Here is a codepen: https://codepen.io/jon424/pen/XWzGNLe When you click “toggle”, you will see the transition happen over the first image, but I would like the same thing to happen over the second image at the same time. Any idea how to do this?

HTML

 <button>Toggle</button>
<div >
  <img  src="https://picsum.photos/200/300">
      <div ></div></div>

<div >
  <img  src="https://picsum.photos/200/302">
      <div ></div></div>

CSS

.parent {
    position: relative;
    width: 300px;
    height: 300px;
    margin: 10px;
}

.child1 {
    position: absolute;
    width: 100%;
    height: 100%;
    bottom: 0;
    left: 0;
}

.child2 {
/*     position: absolute; */
  width: 100%;
    height: 100%;
    bottom: 0;
    left: 0;
}

.covering {
    z-index: 1;
    background: #ffffff;
    transition: max-height 1s ease-in-out;
    max-height:100%;
}

.covered {
  max-height: 0px;
}

.hidden {
  display: none;
}

JS

const firstTarget = document.querySelector(".firstTarget");
const covering = document.querySelector(".covering");

document.querySelector('.covering').classList.add('covered');
document.querySelector('button').addEventListener('click', () => { document.querySelector('.covering').classList.toggle('covered');});

CodePudding user response:

To target many Elements of the same class, use querySelectorAll() and than use NodeList.forEach()

// DOM utility functions:

const ELS = (sel, par) => (par || document).querySelectorAll(sel);
const EL = (sel, par) => (par || document).querySelector(sel);


// Task:

const ELS_covering = ELS(".covering"); // Get them all!

EL('button').addEventListener('click', () => {
  ELS_covering.forEach(el => el.classList.toggle('covered'));
});
.parent {
  position: relative;
  overflow: hidden;
  display: inline-flex;
  width: 200px;
  height: 200px;
  margin: 10px;
}

.child {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

img.child {
  object-fit: cover;
}

.covering {
  z-index: 1;
  background: #eee;
  transition: transform 1s ease-in-out;
  transform: translateY(-100%);
  display: flex; justify-content: center; align-items: center;
}

.covered {
  transform: translateY(0%);
}
<button>Toggle</button>
<br>

<div >
  <img  src="https://picsum.photos/200/300">
  <div >Some text here</div>
</div>

<div >
  <img  src="https://picsum.photos/300/302">
  <div >Lorem Ipsum</div>
</div>

  • Related