Hiding Elements

The last value of display that we'll look at is none. An element with display: none isn't displayed at all, and it takes up no space: the elements after it move up as if it weren't there. It's still in the HTML; the browser just doesn't show it.

Compare it with opacity: 0, which you know from the lesson on colors. That makes an element fully transparent, but the element still takes up its space, so an empty gap stays on the page.

Hiding is useful for content that should appear only at a certain moment: a menu that opens when you hover over it, a tooltip, or the answer to a quiz question. We hide such an element with display: none, and we show it again in a rule with the pseudo-class :hover, which you know from the lesson on selectors.

We've added a short quiz to the Physiology section of the page. Let's hide its answer until the reader hovers over the quiz with the mouse.

Instructions

Create a rule for .answer that sets display: none. The answer disappears, and the quiz box gets smaller, because the hidden paragraph takes up no space.

Create a rule for .quiz:hover .answer that sets display: block. Its selector selects the answer in the quiz, but only while the mouse pointer is over the quiz. Its specificity is higher than that of .answer, so while you hover, it wins. Run the code and hover over the quiz: the answer appears.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10