I’m working on the following files:
JavaScript
x
23
23
1
* {
2
margin: 0;
3
padding: 0;
4
box-sizing: border-box;
5
}
6
7
body {
8
background: #e4e4e4;
9
text-align: center;
10
}
11
12
.content {
13
background: #fff;
14
padding: 20px 40px;
15
width: 60%;
16
margin: 20px auto;
17
}
18
19
.container {
20
border: 1px solid black;
21
padding: 0 40px 40px 40px;
22
background: #fff;
23
}
JavaScript
1
19
19
1
<html lang="en">
2
<head>
3
<meta charset="UTF-8" />
4
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
5
<link rel="stylesheet" href="style.css" />
6
<title>Document</title>
7
</head>
8
<body>
9
<div class="content">
10
<div id="d1" class="container">
11
1
12
<div id="d2" class="container">
13
2
14
<div id="d3" class="container">3</div>
15
</div>
16
</div>
17
</div>
18
</body>
19
</html>
The result I want to achieve is that when I hover a certain div, its background changes to a #ccc
grey color.
However what adds some difficulty is that I want only the area that belongs only to the innermost hovered div to change background color, not the child or parent.
Here is a picture to show the behavior I want for example when hovering the second div:
EDIT: I ALSO WANT THE BACKGROUND COLOR TO BE RESET TO WHITE WHEN THE MOUSE IS OUTSIDE AN AREA
EDIT 2: IS THIS DOABLE WITH ONLY CSS OR IS JAVASCRIPT MANDATORY?
Advertisement
Answer
Some magic using pseudo element and box-shadow:
JavaScript
1
48
48
1
* {
2
margin: 0;
3
padding: 0;
4
box-sizing: border-box;
5
}
6
7
body {
8
background: #e4e4e4;
9
text-align: center;
10
}
11
12
.content {
13
background: #fff;
14
padding: 20px 40px;
15
width: 60%;
16
margin: 20px auto;
17
position:relative;
18
z-index:0; /* this is important */
19
overflow:hidden; /* hide the extra box-shadow */
20
}
21
22
.container {
23
border: 1px solid black;
24
padding: 0 40px 40px 40px;
25
position:relative; /* dont forget relative here */
26
background:#fff;
27
}
28
.container::before,
29
.container::after{
30
content:"";
31
position:absolute;
32
z-index:-1;
33
top:-1px;
34
left:-1px;
35
right:-1px;
36
bottom:-1px;
37
}
38
.container::before {
39
background:grey;
40
}
41
/* on hover */
42
.container:hover::after {
43
box-shadow:0 0 0 200vmax #fff; /* hide the upper div */
44
}
45
.container:hover {
46
background:transparent; /* make the hovered div transaprent to see the "before" element */
47
}
48
/**/
JavaScript
1
9
1
<div class="content">
2
<div id="d1" class="container">
3
1
4
<div id="d2" class="container">
5
2
6
<div id="d3" class="container">3</div>
7
</div>
8
</div>
9
</div>