CSS Snippets

Code Snippet

Fading in a page on load can give site items like a sidebar or icon boxes that load slowly the time to finalize their size/color without the user noticing.

Plus it can give a pleasant look as the page loads.

Fading in the Entire Body of the Page

The way we do this is with CSS animation. The following fades in the body of the page in 0.5 seconds from 0% opacity to 100% opacity.

Place it first thing in your style sheet and adjust the timing as you like.

/* hidden to give the browser time to load the css */
body {
    animation: fadeInBody ease 0.5s; /* fades in over 1/2 second */
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}
@keyframes fadeInBody {
    0% { /* the fade in delays */
        opacity: 0;
    }
    50% { /* the fade in begins */
        opacity: 0;
    }
    100% { /* the fade in ends */
        opacity: 1;
    }
}
/* end hidden to give the browser time to load the css */

Note

The 50% section is unnecessary if you simply want to immediately begin the fade-in without any delay. This will give the fade in a more natural flow.

Fading in a Page Element

If you have just an element on the page you want to fade in, you can place the following in your style sheet.

/* hidden to give the browser time to load the css */
#id-of-your-element { /* specific to the element to fade in */
    animation: fadeInElement ease 1s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
    animation-delay: 1s; /* only if you need to delay the start of the fade in */
    opacity: 0; /* ensures it's initially hidden */
}
@keyframes fadeInElement {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}
/* end hidden to give the browser time to load the css */

Note

The “animation-delay” line is unnecessary. It it used to delay the start of the fade in. In this case, it was added to wait until after the <body> fades in with the first code group above. The 1s delay on the element matches the 1s fade-in on the <body>.


CSS Notes:


We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.