如何在div上用另一个在hover上替换(仅CSS)

问题描述:

我有两个方框,其中一个隐藏,一个可见。我想以某种方式使它工作,即当默认框悬停时,它会淡出并且不显示任何显示框。

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.

有人问过类似的问题,但他们都要求使用JavaScript。我只喜欢CSS。

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

有什么想法吗?提前致谢。

Any idea? Thanks in advance.

您可以使用以下CSS将包装器添加到两个div中:

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

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

您似乎忘记了隐藏 .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>