Zeroic
Zeroic

Reputation: 251

Changing CSS property of an element when hovering another element

I have a div called image. It has a CSS-property visibility:hidden;. I have another button called button.

What I need is when I hover the button, the image changes to visibility:visible;.

Can I do it with CSS or do I have to use JavaScript?

Upvotes: 1

Views: 3120

Answers (4)

Rohit Azad Malik
Rohit Azad Malik

Reputation: 32182

yes you can do this

as like this

HTML

<label for="button">Click here</label>
<input type="checkbox" id="button">

  <div class="one">Show my div</div>

Css

label{
background:green;
  padding:10px;
 }
.one{
width:100px;
  display:none;
  height:100px;
  background:red;
  margin-top:20px;
}
input[type="checkbox"]{
visibility:hidden;

}
input[type="checkbox"]:checked ~ .one{
display:block;
}

Live demo


Updated answer

if you want to just hover than check to this *Demo*

Upvotes: 4

Andrea Turri
Andrea Turri

Reputation: 6500

Note that this is a javascript / jQuery solution:

$(button).hover(function() {
    $('div#image').attr('visibility', 'visible');
}, function() {
    $('div#image').attr('visibility', 'hidden');
});

Upvotes: 2

Mihai Matei
Mihai Matei

Reputation: 24276

You need javascript for that. You can use css if your div is parent for the button, but in your case this is not possible JS

function changeVisibility(objID) {
    var el = document.getElementById(objID);
    if(el.style.visibility == 'hidden') {
        el.style.visibility = 'visible';
        return true;
    }

    el.style.visibility = 'hidden';

}

HTML

<div id="box">Something to show</div>
<input type="button" class="button" onmouseover="changeVisibility('box')" value="Change visibility" />

Upvotes: -1

Ariel
Ariel

Reputation: 26753

You can only do this if the div is a child of the button - which isn't possible.

It's possible if you make it a child of something else (i.e. not a button, do it differently).

However, what browser? All the main ones? Because if you are willing to use only the most modern it's possible by using sibling selectors.

But for mainstream usage you can only do it if the div is a child of the hover element. Note: You can hover anything, it doesn't have to be a button or a link <a>. So that's what I would do - make a div element that looks like a button, and has a child that you want to change.

Upvotes: 0

Related Questions