Kieu Duy
Kieu Duy

Reputation: 439

Showing a div when hover on anchor with css?

Hello I'm working on showing a shopping cart content div.cart-dropdown when I hover the mouse on the a.cart-button.

I can make the div show but when the mouse out the anchor a.cart-button, div.cart-dropdown disappear

Here is the code

.cart-dropdown{
     display:none;
}

a.cart-button:hover + .cart-dropdown{
     display: block;
}
<a href="#" class="cart-button">Cart Button</a>

<div class="cart-dropdown">
  Cart dropdown content
</div>

How can I make the div.cart-dropdown visible when the mouse out a.cart-button

Must I use jQuery ?

Upvotes: 3

Views: 2319

Answers (3)

Ayoub Abid
Ayoub Abid

Reputation: 452

You can add css class on mouseover event that add display block to the div of cart-dropdown:

<script type="text/javascript">
$(".cart-button").one("mouseover", function() {
    $(".cart-dropdown").addClass('permahover');
});
</script>

<style>
.permahover{
    display: block;
}
</style>

Upvotes: 0

Iqbal Pasha
Iqbal Pasha

Reputation: 1316

Try with this code, it may help you

.cart-button {
    position: relative;
    display: inline-block;
}

.cart-dropdown {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    padding: 12px 16px;
    z-index: 1;
}

.cart-button:hover .cart-dropdown {
    display: block;
}
<div class="cart-button">
  <a>Cart Button</a>
  <div class="cart-dropdown">
     Cart dropdown content
  </div>
</div>

Upvotes: 4

GMchris
GMchris

Reputation: 5648

A simple solution is putting both elements in a wrapper, and instead of showing the sibling, when .cart-button is hovered, show a child when the wrapper is.

<div class="dropdown-wrapper">
    <a href="#" class="cart-button">Cart</a>

    <div class="cart-dropdown">
       Cart dropdown content
     </div>
</div>

.dropdown-wrapper:hover .cart-dropdown {
    display: block;
 }

This way, even when the cursor moves to the dropdown menu, it's still within the .dropdown-wrapper, and will keep the menu in display: block

Upvotes: 5

Related Questions