📜  悬停时填充 div (1)

📅  最后修改于: 2023-12-03 15:25:41.447000             🧑  作者: Mango

Hovering to Fill a Div

Have you ever wanted to fill a div with content only when the user hovers over it? Well, with a few lines of code, you can do just that!

The HTML

First let's start with the HTML. You will need a div with a class or id that you can target in your CSS. Inside the div, you can add a placeholder text or image that will be replaced when the user hovers over it. Here's an example:

<div class="container">
  <p>Hover over me!</p>
  <div class="content"></div>
</div>
The CSS

Next, let's add the CSS to hide the content of the div and show the placeholder text or image.

.container {
  position: relative;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('placeholder.png');
}

In the above code, we set the position of the container to relative and the position of the content div to absolute. This will allow us to position the content div on top of the container div. We then set the width and height of the content div to 100% so that it fills up the entire container. Finally, we set the background image of the content div to our placeholder.

The hover effect

Now, let's add the hover effect that will replace the placeholder with the actual content.

.container:hover .content {
  background-image: none;
}

In the above code, we are targeting the container div when the user hovers over it. We then set the background image of the content div to none, which will make it disappear and reveal the actual content that we will add later.

Adding content

Finally, let's add the actual content that will appear when the user hovers over the container.

.container:hover .content {
  background-image: none;
}

.container:hover .content:after {
  content: "This is the actual content!";
  color: #fff;
  font-size: 24px;
  padding: 20px;
  display: block;
}

In the above code, we are targeting the content div after the user hovers over the container. We then use the :after pseudo-element to add the actual content. Here, we have added a simple text message, but you can add any HTML elements, including images and videos.

Conclusion

That's it! With just a few lines of code, you can create a hover effect that fills up a div with content. Here's the final code snippet in markdown format:

<div class="container">
  <p>Hover over me!</p>
  <div class="content"></div>
</div>

.container {
  position: relative;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('placeholder.png');
}

.container:hover .content {
  background-image: none;
}

.container:hover .content:after {
  content: "This is the actual content!";
  color: #fff;
  font-size: 24px;
  padding: 20px;
  display: block;
}