skip to Main Content

I have the following HTML with CSS that changes the background image property of an adjacent div, depending on which h1 is hovered on. Is it possible to apply a transition on the background image while it changes from the default image to the hover image?

I would like to use transition: background-image 500ms ease-in but I’m not sure where this should get placed based in my markup.

    <section class="items">
        <h1 class="art" onmouseout="resetImg()">CSS Art</h1>
        <h1 class="technique" onmouseout="resetImg()">Techniques</h1>
        ..
        ..
    </section>
    <div id="img"></div>

section:has(.art:hover) + #img {
    background-image: url('/images/frog.png') !important;
}

section:has(.technique:hover) + #img {
    background-image: url('/images/scroll.png') !important;
}

2

Answers


  1. I would use a JavaScript function to apply the background-image to an adjacent div. The advantage of using JS instead of just CSS in this case is that you can easily create a variable that points to any other HTML element or CSS class.

    Here is a W3Schools lesson about using onmouseover event listener:
    https://www.w3schools.com/jsref/event_onmouseover.asp

    Here is a W3Schools lesson about using JS to manipulate DOM objects:
    https://www.w3schools.com/js/js_htmldom_css.asp

    Login or Signup to reply.
  2. You can add this code snippet to your CSS code.

    #img {
        transition: background-image 500ms ease-in;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search