CSS Show and Hide with Transition (using :target)

In the last blogpost, I helped to describe the CSS show and hide text posted to StackOverflow. Here I look at adding CSS for a smoother transition by modifying a transition example also on StackOverflow.

/* onload css */

#show
{
display:none; 
}

.wrapper {
    position: relative;
    overflow: hidden;
    width: 300px;
    height: 300px; 
}

.answer
{
position: absolute;
    top: -10px;
    transition: 0.25s;
    opacity:0;
}

In the CSS that styles the HTML page when loaded we first of all hide the text that we want to show later (i.e. the hide button). We also create a wrapper for the text so that it can be invisible by first of all creating what is essentially a box and placing it outside this box, so that it doesn't appear on screen, but so that it doesn't need to be off the actual top of the page as a starting point.

/* click triggered css */
#hide:target {
    display:none;
}

#hide:target + #show
{
    display:inline;
}

#hide:target ~ .wrapper > .answer {
    transition: 0.5s;
    top: 0px; 
    opacity:1; 
}

We then set what is going to happen when the link that targets the element with the hide id is clicked: the answer (which is a child [>] of the wrapper, which is in turn a sibling [~] of the hide element) will fade in and come down as a way of smoothing the appearance. Now for the HTML:

<a href="#hide" id="hide">More...</a>
<a href="#" id="show">Hide</a>
<div class="wrapper">
<p class="answer">
Here is the information you were looking for.</p>
</div>

As you can see the work is being done by the CSS and the only thing that the HTML is doing on its own is resetting the page when you click hide.

Comments