Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS Only – Show Hide an element with hover/unhover action?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading