Home > database >  Is there a way to fade two div elements into one another in CSS?
Is there a way to fade two div elements into one another in CSS?

Time:12-13

If I have two div elements that contain some text and I want them into one another such that as one disappears the other appears and it then repeats how do i go about doing this? I'm not sure where to where to start.

<div id="body">
  <div>My great adventure</div>
  <div>Travel, adventure, leisure</div>
</div>

CodePudding user response:

If you are just talking about non-animated, static elements visually fading into one another, you can use a linear-gradient for the background of ::before and ::after pseudo-elements.

Below is a pure CSS example making use of CSS variables for consistent colors and sizing. The ::before and ::after pseudo-elements fade from the background color to transparent. You can increase the multiplier in margin on the #body > div to decrease the amount of overlap.

body {
  --div-bg: orange;
  --fade-height: 3rem;
  background: white;
}

#body>div {
  position: relative;
  color: black;
  background: var(--div-bg);
  padding: 1rem;
  margin: calc(var(--fade-height) * 1) 0 0;
}

#body>div::before,
#body>div::after {
  content: "";
  position: absolute;
  left: 0;
  right: 0;
  height: var(--fade-height);
}

#body>div::after {
  bottom: calc(var(--fade-height) * -1);
  background: linear-gradient(to bottom, var(--div-bg), transparent);
}

#body>div::before {
  top: calc(var(--fade-height) * -1);
  background: linear-gradient(to top, var(--div-bg), transparent);
}
<div id="body">
  <div>My great adventure</div>
  <div style="--div-bg: #33F;">Travel, adventure, leisure</div>
</div>

CodePudding user response:

Using CSS animations we can achieve this pretty simply.

We will create 2 animations. One that causes the text to fade in initially, and one to cause the text to fade out initially. We will set these animations to loop forever.

You can fine tune the timings and opacity levels to your needs.

.fade {
  position: absolute;
}

#start {
  opacity: 1;
  animation-name: fadeStart;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

#end {
  opacity: 0;
  animation-name: fadeEnd;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

@keyframes fadeStart {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

@keyframes fadeEnd {
  0% {
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
<div id="container">
  <div  id="start">My great adventure</div>
  <div  id="end">Travel, adventure, leisure</div>
</div>

  • Related