vishnu viswanath
vishnu viswanath

Reputation: 3854

CSS : z-index and hover

I have a html file :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="test.css" rel="stylesheet" type="text/css"/>
</head>
<div class="maindiv"><div class="subdiv"><input type="submit" class="button" value="button"/></div></div>
<body>
</body>
</html>

And the test.css file :

@charset "utf-8";
/* CSS Document */

.maindiv {
position:relative;
}
.subdiv {
position:relative;
}
.button:hover {
background-color:#333;
}

Everything was working fine till now. Bg of the button changes color if mouse is over the button.

I added z-index=-1 for the subdiv.

.subdiv {
position:relative;
z-index:-1;
}

After which hover was not working. So i used Firefox Inspector tool to capture the element when mouse is over the button and it was capturing 'div.maindiv'. So i thought of adding z-index=-2 for the maindiv after which it was capturing 'body'

Can some one tell me why it is happening?

Upvotes: 0

Views: 3022

Answers (1)

Harry
Harry

Reputation: 394

Is there any specific reason you are adding z-index: -1 to the subdiv element? Because, adding that to the subdiv is going to place it 'below' the maindiv and body and you wont be able to click on it as a result. The maindiv will cover it so the hover and click event will be not captured by subdiv.

Similarly, making maindiv have z-index: -2 will cause the body element to cover it in the stacking order and therefore again the button will not be clicked.

If you give the body element a position: relative; z-index: -3;, then the button can be clicked by the above logic.

From w3 schools z-index

The z-index property specifies the stack order of an element.

An element with greater stack order is always in front of an element with a lower stack order.

Check out this link as well for more on z-index.

Upvotes: 1

Related Questions