Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace on div with another on hover (CSS ONLY)

Tags:

html

css

display

I have two boxes that one is hidden and one is visible. I want to make it work in a way that when the default box is hover, it fades out and the box with display none gets visible.

Here is the code that doesnt work the way I want it because the once box one is hover, it is still visible, while i want it to go display: none.

.box1, .box2{
  width:100px;
  height 100px;
  border:1px solid black;
  text-align:center;
}

.box1{
  display: block;
}

.box2{
  display: none;
}

.box1:hover ~ .box2{
  display:block;
}
<div class="box1">
  <p>data 1</p>
</div>

<div class="box2">
  <p>data 2</p>
</div>

It could be better if it is animated once the boxes switch.

Similar questions have been asked but they all asked for JavaScript. I prefer CSS only.

Any idea? Thanks in advance.

like image 444
DannyBoy Avatar asked Dec 14 '22 19:12

DannyBoy


1 Answers

You can add a wrapper to the two div with the following css:

.wrapper {
  width: auto;
  display: inline-block;
  background-color: red; //for visuals
}

And you seem to forgot to hide .box1

.box1,
.box2 {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  text-align: center;
}

.box1 {
  display: block;
}

.box2 {
  display: none;
}

.wrapper {
  width: auto;
  display: inline-block;
  background-color: red;
}

.wrapper:hover .box1 {
  display: none;
}

.wrapper:hover .box2 {
  display: block;
}
<div class="wrapper">
  <div class="box1">
    <p>data 1</p>
  </div>

  <div class="box2">
    <p>data 2</p>
  </div>
</div>
like image 72
Carl Binalla Avatar answered Jan 06 '23 07:01

Carl Binalla