0

There is wrapper div contains two div with different text. I need to change the text on hover and the gol is to place text2 div at the same position as text1.

.wrapper {
  background: red;
  width: max-content;
  padding: 20px;
}

.text1 {
  background: green;
  opacity: 1;
  transition: all 0.5s;
}

.text2 {
  background: yellow;
  opacity: 0;
  transition: all 0.5s;
}

.wrapper:hover>.text1 {
  opacity: 0;
}

.wrapper:hover>.text2 {
  opacity: 1;
}
<div class="wrapper">
  <div class="text1">Text 1</div>
  <div class="text2">Text 2</div>
</div>

How do I overlap 2 text-divs in one wrapper div?

This is not exactly the same question, in the link author sets width: 100%; height: 100%; but I have to adjust the wrapper height and width to text size somehow.

mr_blond
  • 1,586
  • 2
  • 20
  • 52
  • For your above simple example, you could use `transform: translateY(-100%);` on your text2 but when there are more content this method might not work too well, you can position one of them absolute and position it on top of the other – Huangism Aug 19 '19 at 20:32
  • @Huangism not exactly, in the link author sets width: 100%; height: 100%; but I have to adjust the wrapper height and width to text size somehow. – mr_blond Aug 19 '19 at 20:41
  • It shows you how to overlay an element on top of another which is essentially your issue. Plus it has all the explanation in the other answer as well, good read to learn how it works – Huangism Aug 19 '19 at 20:43
  • If you really go by the exact sizing of everything then there barely will be any duplicates, the concept is there and if you actually did any research, you wouldn't be asking this in the first place – Huangism Aug 19 '19 at 20:49

1 Answers1

0

You could position the second text div absolutely, giving it a top position equal to the padding you set on the wrapper div:

.wrapper {
  background: red;
  width: max-content;
  padding: 20px;
}

.text1 {
  background: green;
  opacity: 1;
  transition: all 0.5s;
}

.text2 {
  background: yellow;
  opacity: 0;
  transition: all 0.5s;
}

.wrapper:hover>.text1 {
  opacity: 0;
}

.wrapper:hover>.text2 {
  opacity: 1;
}

.text2 {
  position: absolute;
  top: 20px;
}

.wrapper {
  position: relative;
}
<div class="wrapper">
  <div class="text1">Text 1</div>
  <div class="text2">Text 2</div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272