Creating a Confetti Effect with CSS

Setting Up Our Files

To begin, create a folder for your project and add two files: index.html and style.css. In the index.html file, include the basic markup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Confetti Effect</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="confetti-container"></div>
</body>
</html>

In the style.css file, we’ll start by targeting the root, body, and HTML elements:

:root {
    --bg: #f0f0f0;
}

body {
    margin: 0;
    padding: 0;
    background-color: var(--bg);
}

html {
    font-size: 16px;
}

Creating Different Shapes

To add some variety to our confetti effect, we’ll create several shapes using CSS. Let’s start with a square:

.square {
    width: 20px;
    height: 20px;
    background-color: var(--bg);
    transform: rotate(45deg);
}

Next, we’ll create a rectangle:

.rectangle {
    width: 30px;
    height: 10px;
    background-color: var(--bg);
}

We can also create more complex shapes like hexagrams, pentagrams, and dodecagrams using CSS transforms and pseudo-elements.

Animating Shapes

To create a waterfall effect, we’ll animate our shapes using CSS keyframes:

.confetti i {
    animation: confetti 2s infinite;
}

@keyframes confetti {
    0% {
        transform: translateY(-100%);
    }
    100% {
        transform: translateY(100vh);
    }
}

Randomizing Shapes and Animation

To add an extra layer of realism to our confetti effect, we’ll randomize the shapes, animation duration, and colors. We can achieve this by passing variables directly to the shapes using HTML and CSS.

Bonus Styles

We can also add an option for the user to pause the confetti animation by adding a checkbox:

label input[type="checkbox"]:checked ~.confetti-container {
    animation-play-state: paused;
}

By following these steps, you can create a stunning confetti effect using only CSS and HTML. This effect can be used to add a touch of celebration to your website or application.

Leave a Reply