Archive
HowTo: Show block on anchor hover and click to keep open with CSS
I was looking for a way to show a hidden HTML element with just CSS (no Javascript) when mouse hovers over an anchor (say over a “more…” note), while at the same time also supporting touch-only (no mouse) clients, where clicking should show (and keep open) that same element.
I ended up combining solutions and comments from
https://stackoverflow.com/questions/18849520/css-show-hide-content-with-anchor-name and
https://stackoverflow.com/questions/5210033/using-only-css-show-div-on-hover-over-a#5210074
into
https://jsfiddle.net/birbilis/23nt74se/
Achieved the following behaviour:
- Can hover over an anchor to temporarily show its respective more info block
- Once the info block is open, hovering over that one too (having left the anchor above it) keeps it open (useful to select and copy content from the item)
- Can click on an anchor to show its respective more info block and keep it open. Only one such block is kept open at a time. If multiple exist and you click on another’s anchor, the last one is shown and kept open instead (this doesn’t affect what is temporarily also shown via the hover mechanism).
Notes:
- Could show the item inside the flow or float, e.g. using inline-block instead of block (https://www.w3schools.com/css/css_inline-block.asp)
- I use the :target CSS selector in a bit different way than the original suggestion had, I just set the anchor to jump to itself for easier maintenance of IDs and targets and maintenance-free CSS when adding more targets.
- The anchor with the “openhelp” class must be placed immediately before the item with the help class, since .openhelp:hover + .help is used (https://www.w3schools.com/cssref/sel_element_pluss.asp)
At Trafilm Gallery Metadata forms I ended up using yet another variation with simpler syntax, where the anchor and help text is placed inside a parent div that has text for the item the help is about and that div is marked with class “question”. See https://jsfiddle.net/birbilis/s3kaknt9/ – When the parent questions already have an ID, this has the benefit that you don’t need to add an ID to the anchor, just an href, plus when clicked it scrolls to the parent item (the question) instead of to the help item that is at the bottom of it which would put the question text out of the view when the help link is clicked, if the question is far enough down the page for it to scroll when targetted by the openhelp anchor.