user2082422
user2082422

Reputation: 129

Show/hide appearing div using pure CSS3

I have encountered a problem that bothers me for sereval days now.

In an ASP.NET MVC4 project I check the ViewBag every time in the _Layout view for a result message, and if there's one, I render a div for the message text. I'd like to animate this div so it appears and disappears in about 3sec. I want to make this work with pure css, if that's possible.

Here are my code fragments:

CSS:

#result-message-div {
margin: 50px 0px auto;
width: auto;
background-color: #ffa11f;
text-align: center;
font-size: small;
font-weight: bold;
-webkit-animation: resultMessageAnimation 3s;
}

@-webkit-keyframes resultMessageAnimation {
0% { height: 0%; }
15% { height: 100%; }
75% { height: 100%; }
100% { height: 0%; }
}

Razor:

@if (ViewBag.ResultMessage != null)
{
    <div id="result-message-div">
        @ViewBag.ResultMessage
    </div>
}

With this code, the div appears indeed, but no animations happens and it remains visible. Am I on the right track with this after all?

Upvotes: 1

Views: 118

Answers (1)

xec
xec

Reputation: 18024

You are very close! The issue is you are using 100% for the height. Basically, this means 100% of its parent, which by default only is as big as its content (so, a chicken-and-the-egg sort of problem).

If you can set a static height for your message box i suspect your code should work just fine.

#result-message-div {
    margin: 50px 0px auto;
    /* width: auto; // not necessary as 'auto' is the default value */
    background-color: #ffa11f;
    text-align: center;
    font-size: small;
    font-weight: bold;
    height: 0; /* this value will apply after animation is done  */
    overflow: hidden; /* important, or  text will always show */
    [-webkit-/-moz-]animation: resultMessageAnimation 3s;
}

@[-webkit-/-moz-]keyframes resultMessageAnimation {
    0% { height: 0; }
    15% { height: 20px; } /* note static px value instead of % */
    75% { height: 20px; }
    100% { height: 0; }
}

http://jsfiddle.net/NufRJ/1/

Upvotes: 2

Related Questions