Welcome to a quick tutorial on how to create custom error messages with pure CSS. By now, you should have experienced the intrusive default Javascript alert box. Every time it shows up, users get scared away.
We can create a custom non-intrusive error message with HTML <div>.
<div style="border: 1px solid darkred; background: salmon">
<i>⚠</i> ERROR!
</div>
Yep, it is that simple. Let us “improve and package” this simple error notification bar so you can reuse it easily in your project – Read on!
ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.
TABLE OF CONTENTS
DOWNLOAD & NOTES
Firstly, here is the download link to the example code as promised.
QUICK NOTES
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.
EXAMPLE CODE DOWNLOAD
Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
CSS-ONLY ERROR NOTIFICATIONS
Let us start with the raw basics by creating notification bars with just pure CSS and HTML.
1) BASIC NOTIFICATION BAR
1A) THE HTML
1-basic.html
<div class="bar">Plain message</div>
<div class="bar info">Information message</div>
<div class="bar success">Successful message</div>
<div class="bar warn">Warning message</div>
<div class="bar error">Error message</div>
That is actually all we need to create a custom error message, an HTML <div> with the notification message inside. Take note of the bar and info | success | warn | error CSS classes – We will use these to build the notification bar.
1B) THE CSS
error-bar.css
/* (A) THE BASE */
.bar {
padding: 10px;
margin: 10px;
color: #333;
background: #fafafa;
border: 1px solid #ccc;
}
/* (B) THE VARIATIONS */
.info {
color: #204a8e;
background: #c9ddff;
border: 1px solid #4c699b;
}
.success {
color: #2b7515;
background: #ecffd6;
border: 1px solid #617c42;
}
.warn {
color: #756e15;
background: #fffbd1;
border: 1px solid #87803e;
}
.error {
color: #ba3939;
background: #ffe0e0;
border: 1px solid #a33a3a;
}
The CSS is straightforward as well –
.baris literally the “basic notification bar” with padding, margin, and border..info | .success | .warn | .errorsets various different colors to fit the “level of notification”.
Feel free to changes these to fit your own website’s theme.
1C) THE DEMO
Plain message
Information message
Successful message
Warning message
Error message
2) ADDING ICONS
2A) THE HTML
2-icon.html
<div class="bar">
<i class="ico">☀</i> Plain message
</div>
<div class="bar info">
<i class="ico">ℹ</i> Information message
</div>
<div class="bar success">
<i class="ico">✔</i> Successful message
</div>
<div class="bar warn">
<i class="ico">⚠</i> Warning message
</div>
<div class="bar error">
<i class="ico">☓</i> Error message
</div>
To add icons to the notification bar, we simply prepend the messages with <i class="ico">&#XXXX</i>. For those who do not know – That &#XXXX is a “native HTML symbol”, no need to load extra libraries. Do a search for “HTML symbols list” on the Internet for a whole list of it.
P.S. Check out Font Awesome if you want more icon sets.
2B) THE CSS
error-bar.css
/* (C) ICONS */
i.ico {
display: inline-block;
width: 20px;
text-align: center;
font-style: normal;
font-weight: bold;
}
Just a small addition to position the icon nicely.
2C) THE DEMO
☀ Plain message
ℹ Information message
✔ Successful message
⚠ Warning message
☓ Error message
JAVASCRIPT ERROR NOTIFICATIONS
The above notification bars should work sufficiently well, but here are a few small improvements if you are willing to throw in some Javascript.
3) ADDING CLOSE BUTTONS
3A) THE HTML
3-close.html
<div class="bar">
<div class="close" onclick="this.parentElement.remove()">X</div>
<i class="ico">☀</i> Plain message
</div>
<div class="bar info">
<div class="close" onclick="this.parentElement.remove()">X</div>
<i class="ico">ℹ</i> Information message
</div>
<div class="bar success">
<div class="close" onclick="this.parentElement.remove()">X</div>
<i class="ico">✔</i> Successful message
</div>
<div class="bar warn">
<div class="close" onclick="this.parentElement.remove()">X</div>
<i class="ico">⚠</i> Warning message
</div>
<div class="bar error">
<div class="close" onclick="this.parentElement.remove()">X</div>
<i class="ico">☓</i> Error message
</div>
Not much of a difference here, except that we now add a <div class="close"> that will act as the close button.
3B) THE CSS
error-bar.css
/* (D) CLOSE BUTTON */
.bar { position: relative; }
div.close {
position: absolute;
top: 30%;
right: 10px;
color: #888;
cursor: pointer;
}
There is not much added to the CSS as well. We simply position the close button to the right of the notification bar, and that’s about it.
3C) THE DEMO
4) PACKAGED ERROR NOTIFICATIONS
4A) THE HTML
4-js.html
<!-- (A) LOAD CSS + JS -->
<link href="error-bar.css" rel="stylesheet">
<script src="error-bar.js"></script>
<!-- (B) HTML CONTAINER -->
<div id="demo"></div>
<!-- (C) FOR TESTING -->
<script>
let demo = document.getElementById("demo");
ebar({ target: demo, msg: "Plain" });
ebar({ lvl: 1, target: demo, msg: "Information" });
ebar({ lvl: 2, target: demo, msg: "Success" });
ebar({ lvl: 3, target: demo, msg: "Warning" });
ebar({ lvl: 4, target: demo, msg: "Error" });
</script>
The notification bar is has gotten rather messy, and it is a pain to manually copy-paste them. So why not package everything into an easy-to-use Javascript ebar() function?
targetTarget HTML container to generate the error message.msgThe error or notification message.lvlOptional, error level.
4B) THE JAVASCRIPT
error-bar.js
function ebar (instance) {
// target : target html container
// msg : notification message
// lvl : (optional) 1-info, 2-success, 3-warn, 4-error
// (A) CREATE NEW NOTIFICATION BAR
let bar = document.createElement("div");
bar.classList.add("bar");
// (B) ADD CLOSE BUTTON
let close = document.createElement("div");
close.innerHTML = "X";
close.classList.add("close");
close.onclick = () => bar.remove();
bar.appendChild(close);
// (C) SET "ERROR LEVEL"
if (instance.lvl) {
let icon = document.createElement("i");
icon.classList.add("ico");
switch (instance.lvl) {
// (C1) INFO
case 1:
bar.classList.add("info");
icon.innerHTML = "ℹ";
break;
// (C2) SUCCESS
case 2:
bar.classList.add("success");
icon.innerHTML = "☑";
break;
// (C3) WARNING
case 3:
bar.classList.add("warn");
icon.innerHTML = "⚠";
break;
// (C4) ERROR
case 4:
bar.classList.add("error");
icon.innerHTML = "☓";
break;
}
bar.appendChild(icon);
}
// (D) NOTIFICATION MESSAGE
let msg = document.createElement("span");
msg.innerHTML = instance.msg;
bar.appendChild(msg);
// (E) ADD BAR TO CONTAINER
instance.target.appendChild(bar);
}
This may look complicated, but this function essentially just creates all necessary notification bar HTML.
4C) THE DEMO
LINKS & REFERENCES
- 6 Ways To Display Messages In HTML JS – Code Boxx
- 2 Ways To Display A Message After Submitting HTML Form – Code Boxx
- 10 Free CSS & JS Notification Alert Code Snippets -SpeckyBoy
- CSS Tips and Tricks for Customizing Error Messages! – Cognito Forms
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
This tutorial will show you how to create and customize error messaging for various form elements. In this tutorial, we will customize everything from a basic error message to input field errors and tooltips. The best part? We will be using only CSS for customizations – that means no images or javascript required!
HTML
Below is the markup for the form elements we will be creating error messaging for. This is all of the HTML used throughout this tutorial. Copy and paste this code into your working file:
<!-- Basic Error Message --> <div class="error-message"> <span class="error-text">Checkout could not be completed. Please check your login information and try again.</span> </div> <!-- Input Field Error --> <div class="input-group error"> <label>Password *</label> <input type="text"> <div class="error-message">Password is a required field.</div> </div> <!-- Input Field Error with Tooltip --> <div class="input-group error"> <label>Quantity</label> <input type="text"> <div class="error-tip">Enter a quantity</div> </div>
CSS
Now onto my personal favorite: the CSS. We will keep the basic functionality of the form elements but completely customize their appearance. In the end, they will stand on their own as custom design elements that thoughtfully guide the user through the form process, making it as straightforward and painless as possible.
Basic Error Message
Let’s start with a basic error message. We are going to customize the HTML above to look like this:
This is what we start out with, by default, after adding the HTML:
Customizing a basic error message is really simple. All we have to do is give our text a colored background and a couple font styles using CSS. To style the error message background, add the following styles to your CSS stylesheet:
.error-message {
background-color: #fce4e4;
border: 1px solid #fcc2c3;
float: left;
padding: 20px 30px;
}
Now let’s style the text itself by adding the following font styles:
.error-text {
color: #cc0033;
font-family: Helvetica, Arial, sans-serif;
font-size: 13px;
font-weight: bold;
line-height: 20px;
text-shadow: 1px 1px rgba(250,250,250,.3);
}
That’s it! Keep reading to learn how to style input field and tooltip errors.
Input Field Error
Now that we have our basic error message styled, let’s work on input field errors. This is what the final product will look like:
And this is what we start out with by default:
First, we want to override the browser’s default styles. Add the following CSS to give your input field a custom look:
/* Basic Input Styling */
.input-group {
color: #333;
float: left;
font-family: Helvetica, Arial, sans-serif;
font-size: 13px;
line-height: 20px;
margin: 0 20px 10px;
width: 200px;
}
label {
display: block;
margin-bottom: 2px;
}
input[type=text] {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 13px;
height: 33px;
margin: 0;
padding: 0 0 0 15px;
width: 100%;
}
Next, we need to add the styling for the error message that displays when a user does not correctly fill out an input field (i.e. the “This is a required field” message):
.error-message {
color: #cc0033;
display: inline-block;
font-size: 12px;
line-height: 15px;
margin: 5px 0 0;
}
Lastly, add the error-specific styling for the input field elements:
.error label {
color: #cc0033;
}
.error input[type=text] {
background-color: #fce4e4;
border: 1px solid #cc0033;
outline: none;
}
Input Field Error with Tooltip
The last element we’re tackling is the tooltip. It is slightly more complicated than the others but well worth the effort. We will also be utilizing Sass nesting to better organize our code, and because we are only using SCSS it is 100% editable and scalable.
Once we are done, the tooltip will look like this:
And by default, this is what we start with after adding the HTML:
First, we override the browser’s default styles with our own custom styling:
/* Basic Input Styling */
.input-group {
color: #333;
float: left;
font-family: Helvetica, Arial, sans-serif;
font-size: 13px;
line-height: 20px;
margin-bottom: 10px;
width: 100%;
}
label {
display: block;
margin-bottom: 5px;
}
input[type=text] {
background: #fff;
border: 1px solid #ccc;
color: #333;
float: left;
font-family: Helvetica, Arial, sans-serif;
font-size: 13px;
height: 33px;
line-height: 20px;
margin: 0;
padding: 0 0 0 15px;
width: 45px;
}
Just like our previous example, we need to add the tooltip error message styling that displays when a form error occurs. Note: we are using Sass here to nest the tooltip’s left arrow properties. This comes in handy when trying to keep track of which values are assigned to the tooltip specifically:
/* Tooltip Styling */
.error-tip {
background-color: #fce4e4;
border: 1px solid #fcc2c3;
border-radius: 7px;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
display: inline;
color: #cc0033;
float: left;
font-weight: bold;
line-height: 24px;
position: relative;
padding: 7px 11px 4px;
margin-left: 17px;
// Left Arrow Styling Starts Here
&:after, &:before {
content: '';
border: 7px solid transparent;
position: absolute;
top: 11px;
}
&:after {
border-right: 7px solid #fce4e4;
left: -14px;
}
&:before {
border-right: 7px solid #fcc2c3;
left: -15px;
}
} // end .error-tip
Now all that’s left to do is define the input’s error-specific styling. Again, we will nest these styles under an “error” class selector to make classification and future changes easier:
/* Error Styling */
.error.input-group {
label {
color: #cc0033;
font-weight: bold;
}
input {
border: 2px solid #cc0033;
line-height: 37px;
outline: none;
}
.status {
display: none;
}
.error-tip {
display: inline;
}
} // end .error
And that’s it! All the code you need to customize error messaging for default form elements. To experiment with the final results and copy and paste to your heart’s content (without fear of breaking anything), jump on over to Codepen by selecting any of the tutorial links below.
Codepen/Tutorial Links
All: codepen.io/seskew/
Basic Error Message: codepen.io/seskew/pen/akhLx
Input Field Error: codepen.io/seskew/pen/XKJKNQ
Input Field Error with Tooltip: codepen.io/seskew/pen/NrPNBp
How do I style the HTML form validation error messages with CSS?
TylerH
20.8k66 gold badges76 silver badges101 bronze badges
asked Mar 16, 2011 at 17:01
0
Currently, there is no way to style those little validation tooltips. The only other option, which is what I have chosen to do, is to disable the browser validation all together for now and rely on my own client-side validation scripts.
According to this article:
http://blog.oldworld.fr/index.php?post/2010/11/17/HTML5-Forms-Validation-in-Firefox-4
«The simplest way to opt out is to add the novalidate attribute to your <form>. You can also set formnovalidate on your submit controls.»
alex
480k201 gold badges878 silver badges984 bronze badges
answered May 20, 2011 at 13:54
RaminRamin
2234 silver badges10 bronze badges
1
There is currently no way to achieve this.
Chrome up until version 27 provided a native look and feel for their validation error speech bubbles. The error bubble is made up of four containing elements that are not normative elements. These four elements are style-able via pseudo-elements that apply to separate sections of the bubble:
::-webkit-validation-bubble
::-webkit-validation-bubble-arrow-clipper
::-webkit-validation-bubble-arrow
::-webkit-validation-bubble-message
With the release of Chrome v28, they removed these non-standard selectors: https://bugs.chromium.org/p/chromium/issues/detail?id=259050
Quentin
916k126 gold badges1213 silver badges1337 bronze badges
answered Jul 2, 2011 at 8:15
EstelleEstelle
691 silver badge2 bronze badges
4
Use pseudo selectors, as easwee said. For example, to make the form element green when valid, and red when invalid, do something like this:
:invalid {
background: #ffdddd;
}
:valid{
background:#ddffdd;
}
If you need a full reference of these, head to Mozilla Developer Network
TylerH
20.8k66 gold badges76 silver badges101 bronze badges
answered Mar 29, 2011 at 22:01
RemixzRemixz
1431 silver badge5 bronze badges
1
A required field will be invalid until the correct input is entered. A field that isn’t required but has validation, such as a URL field, will be valid until text is entered.
input:invalid {
border:solid red;
}
for more info http://msdn.microsoft.com/en-us/library/ie/hh772367(v=vs.85).aspx
answered May 1, 2014 at 19:00
GANIGANI
2,0034 gold badges36 silver badges69 bronze badges
1
HTML5 provides form validation features that make it easy for developers to validate user input on the client-side. The default error messages that are displayed for invalid form inputs are not very visually appealing, and styling them with CSS can greatly enhance the user experience. There are several methods to style HTML5 form validation error messages with CSS, and each method has its own advantages and disadvantages.
Method 1: Using the :invalid and :valid pseudo-classes
Styling HTML5 form validation error messages with CSS can be done using the :invalid and :valid pseudo-classes. Here’s how:
- First, select the
:invalidpseudo-class to target the input element with an invalid value.
input:invalid {
border-color: red;
}
This code will add a red border to the input element when it has an invalid value.
- To style the error message that appears when the input is invalid, use the
:invalidpseudo-class on the::beforepseudo-element of thespanelement that contains the error message.
input:invalid + span::before {
content: "Please enter a valid value";
color: red;
}
This code will display the error message «Please enter a valid value» in red text before the span element when the input is invalid.
- To style the input element when it has a valid value, use the
:validpseudo-class.
input:valid {
border-color: green;
}
This code will add a green border to the input element when it has a valid value.
- To style the success message that appears when the input is valid, use the
:validpseudo-class on the::beforepseudo-element of thespanelement that contains the success message.
input:valid + span::before {
content: "Thank you for entering a valid value";
color: green;
}
This code will display the success message «Thank you for entering a valid value» in green text before the span element when the input is valid.
Here’s the complete code example:
input:invalid {
border-color: red;
}
input:invalid + span::before {
content: "Please enter a valid value";
color: red;
}
input:valid {
border-color: green;
}
input:valid + span::before {
content: "Thank you for entering a valid value";
color: green;
}
By using these pseudo-classes, you can easily style HTML5 form validation error messages and success messages with CSS.
Method 2: Using JavaScript and the setCustomValidity() method
To style HTML5 form validation error messages with CSS using JavaScript and the setCustomValidity() method, follow these steps:
- Create a form in HTML with input fields that require validation.
<form>
<label for="username">Username:</label>
<input type="text" id="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" required>
<br>
<button type="submit">Submit</button>
</form>
- Add CSS styles for the input fields and error messages.
input:invalid {
border: 2px solid red;
}
input:valid {
border: 2px solid green;
}
input:invalid + span::before {
content: "⚠ ";
color: red;
}
- Use JavaScript to customize the error messages using the setCustomValidity() method.
const form = document.querySelector("form");
const username = document.querySelector("#username");
const password = document.querySelector("#password");
username.addEventListener("input", function(event) {
if (username.validity.patternMismatch) {
username.setCustomValidity("Username must contain only letters and numbers.");
} else {
username.setCustomValidity("");
}
});
password.addEventListener("input", function(event) {
if (password.validity.patternMismatch) {
password.setCustomValidity("Password must contain at least one uppercase letter, one lowercase letter, and one number.");
} else {
password.setCustomValidity("");
}
});
form.addEventListener("submit", function(event) {
if (!form.checkValidity()) {
event.preventDefault();
}
});
In the above code, we first select the form and the input fields that require validation. We then add event listeners to the input fields that trigger when the user types into them. If the input is invalid, we use the setCustomValidity() method to set a custom error message. If the input is valid, we set the error message to an empty string. Finally, we add an event listener to the form’s submit button that prevents the form from submitting if it is not valid.
With these steps, you can style HTML5 form validation error messages with CSS using JavaScript and the setCustomValidity() method.
Method 3: Using JavaScript and the :after pseudo-element
To style HTML5 form validation error messages with CSS using JavaScript and the :after pseudo-element, follow these steps:
- Select the input element that needs validation styling using JavaScript.
const inputElement = document.querySelector('input');
- Add an event listener to the input element to listen for validation errors.
inputElement.addEventListener('invalid', (event) => {
// code to style the validation error message
});
- In the event listener, create a new CSS pseudo-element using JavaScript.
const errorIcon = document.createElement('span');
errorIcon.classList.add('error-icon');
- Style the pseudo-element using CSS.
.error-icon:after {
content: '⚠️';
color: red;
margin-left: 5px;
}
- Append the pseudo-element to the input element.
inputElement.parentNode.appendChild(errorIcon);
- Position the pseudo-element relative to the input element using CSS.
input + .error-icon {
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
}
Here is the complete code example:
const inputElement = document.querySelector('input');
inputElement.addEventListener('invalid', (event) => {
const errorIcon = document.createElement('span');
errorIcon.classList.add('error-icon');
inputElement.parentNode.appendChild(errorIcon);
});
.error-icon:after {
content: '⚠️';
color: red;
margin-left: 5px;
}
input + .error-icon {
position: absolute;
top: 50%;
right: 5px;
transform: translateY(-50%);
}
Method 4: Using a custom library such as SweetAlert2
To style HTML5 form validation error messages with CSS using a custom library such as SweetAlert2, follow these steps:
- First, include SweetAlert2 in your HTML file by adding the following code in the head section:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.all.min.js"></script>
- Next, add the following JavaScript code to your file to customize the validation error messages:
// Customize validation error messages
const invalidFields = document.querySelectorAll(':invalid');
invalidFields.forEach((field) => {
const message = field.validationMessage;
const swal = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
swal.fire({
type: 'error',
title: message
});
});
- Finally, add the following CSS code to style the error message:
.swal2-popup {
background-color: #f8d7da;
color: #721c24;
border-color: #f5c6cb;
}
This will customize the validation error messages using SweetAlert2 and style them with CSS.
- Главная»
- Уроки»
- CSS»
- Создание красивых сообщений с помощью CSS
- Метки урока:
- подсказки
- сообщения
В данном уроке Вы научитесь создавать красивые сообщения с помощью CSS. Кроме этого, Вы также узнаете как ими правильно пользоваться.
Давайте начнем с типов сообщений
1. Информационные сообщения
Цель этих сообщений информирования пользователя. Такие сообщения должны быть голубыми, так как люди ассоциируют этот цвет с информацией. Это может быть любая информация, которая может быть полезна юзеру.
2. Сообщения об успехе
Сообщения об успехе должны быть показаны после того, как юзер успешно выполнил какую-либо операцию. Успешно — означает полностью и без ошибок. Обычно такие сообщения зеленого цвета.
3. Сообщения-предупреждения
Подобные сообщения должны быть показаны пользователю если операция не может быть завершена. Обычно они желтого цвета.
4. Сообщения об ошибке
Сообщения об ошибке должны быть показаны только в том случае, если операцию невозможно выполнить. Красный идеальный цвет для этого, так как многие ассоциируют этот цвет с тревогой 
5. Сообщения проверки
Еще один тип сообщений. Я предпочел для них оранжевый цвет. Подобные сообщения показывают пользователю его ошибки (например, при заполнении форм).
Теперь давайте посмотрим как такие сообщения создать
Нам понадобится следующий код CSS:
body{
font-family:Arial, Helvetica, sans-serif;
font-size:13px;
}
.info, .success, .warning, .error, .validation {
border: 1px solid;
margin: 10px 0px;
padding:15px 10px 15px 50px;
background-repeat: no-repeat;
background-position: 10px center;
}
.info {
color: #00529B;
background-color: #BDE5F8;
background-image: url('info.png');
}
.success {
color: #4F8A10;
background-color: #DFF2BF;
background-image:url('success.png');
}
.warning {
color: #9F6000;
background-color: #FEEFB3;
background-image: url('warning.png');
}
.error {
color: #D8000C;
background-color: #FFBABA;
background-image: url('error.png');
}
.validation {
color: #D63301;
background-color: #FFCCBA;
background-image: url('validation.png');
}
Данный код можно вставить как в тот же файл, так и вынести в таблицу стилей.
Теперь нам достаточно в теле документа создать слой с необходимым классом:
<div class="info">Info message</div>
<div class="success">Successful operation message</div>
<div class="warning">Warning message</div>
<div class="error">Error message</div>
<div class="validation">Validation message</div>
Заключение
Сообщения очень важный элемент любого интерфейса. Очень часто их вообще не используют. Не повторяйте эту ошибку и пользуйтесь подобными сообщениями! И желаю Вашим пользователям как можно меньше сообщений об ошибках!!! 
5 последних уроков рубрики «CSS»
-
Забавные эффекты для букв
Небольшой эффект с интерактивной анимацией букв.
-
Реализация забавных подсказок
Небольшой концепт забавных подсказок, которые реализованы на SVG и anime.js. Помимо особого стиля в примере реализована анимация и трансформация графических объектов.
-
Анимированные буквы
Эксперимент: анимированные SVG буквы на базе библиотеки anime.js.
-
Солнцезащитные очки от первого лица
Прикольный эксперимент веб страницы отображение которой осуществляется “от первого лица” через солнцезащитные очки.
-
Раскрывающаяся навигация
Экспериментальный скрипт раскрывающейся навигации.













