I want to show / hide a variable on hover with help of CSS only. Here's my html:
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<p>Hover here to see magic</div>
<div>Hello World</div>
</body>
</html>
Here's my css:
:root {
--show-state: none;
--p-color: black;
}
body {
padding: 2rem;
}
body > div {
color: var(--p-color);
display: var(--show-state);
}
body > p {
border: 2px solid var(--p-color);
cursor: pointer;
padding: 1rem;
color: var(--p-color);
}
body > p:hover {
--p-color: blue;
--show-state: block;
}
When I hover to the element, the paragraph color changes however since --show-state sets to block I should be able to see the div but it still remains invisible:
I have also attached code sandbox to try it on: https://codesandbox.io/s/html-code-editor-forked-hv5teh?file=/style.css:0-251
Can someone tell me what am I doing wrong or if this won't be possible at all only via CSS?
CodePudding user response:
You are changing the variables for the p element, not for the whole body (or :root) so the div isnt affected.
However, since the div comes after the p element and is its immediate sibling you can use the combinator to affect the settings of the CSS variables for that div.
:root {
--show-state: none;
--p-color: black;
}
body {
padding: 2rem;
}
body>div {
color: var(--p-color);
display: var(--show-state);
}
body>p {
border: 2px solid var(--p-color);
cursor: pointer;
padding: 1rem;
color: var(--p-color);
}
body>p:hover div {
--p-color: blue;
--show-state: block;
}
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="./style.css" />
</head>
<body>
<p>Hover here to see magic</div>
<div>Hello World</div>
</body>
</html>