reply View all Tutorials & Projects

How to Add an Alert Box to Your Websites with HTML & CSS

In today's video I'll be showing you how to add an alert box to your websites using HTML, CSS and JavaScript. These are available in different styles such as a success green, warning yellow or error red. Use these with your favourite framework or library such as React, Vue or Svelte to add alert messages for your HTML forms 😀

Video Tutorial

Source Code

You can find the source code for this video below.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Add an Alert Box to Your Website</title>
	<link rel="stylesheet" href="main.css">
	<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />
</head>
<body>
	<div class="container">
		<div class="alert alert-error">
			<div class="alert-icon">
				<span class="material-symbols-outlined">
					info
				</span>
			</div>
			<div class="alert-text">
				Add Your Custom Message Here
			</div>
		</div>
	</div>

	<script>
		const alertBox = document.querySelector(".alert");

		setTimeout(() => alertBox.remove(), 1000);
	</script>
</body>
</html>
main.css
.material-symbols-outlined {
	font-variation-settings:
	'FILL' 0,
	'wght' 400,
	'GRAD' 0,
	'opsz' 48
}

.container {
	margin: 0 auto;
	max-width: 1000px;
}

.alert {
	--foreground-color: #222222;
	--background-color: #eeeeee;

	display: flex;
	align-items: center;
	padding: 1em;
	box-sizing: border-box;
	border-radius: 5px;
	width: 100%;
	background-color: var(--background-color);
}

.alert-icon {
	display: flex;
	align-items: center;
}

.alert-text {
	margin-left: 1em;
	font-size: 1.15em;
	font-weight: 500;
	font-family: 'Lexend', sans-serif;
}

.alert-icon .material-symbols-outlined,
.alert-text {
	color: var(--foreground-color);
}

.alert-warning {
	--foreground-color: #000000;
	--background-color: #ecd103;
}

.alert-success {
	--foreground-color: #ffffff;
	--background-color: #46b63e;
}

.alert-error {
	--foreground-color: #ffffff;
	--background-color: #cb0000;
}

If you have any questions about this code, please leave a comment on the video.