How to Change Input Field Border Color on Focus in HTML and CSS

In this tutorial, we will learn how to change input field border color on focus in HTML and CSS. When you are working on a website or creating a login form, you want to create better border focus styles on many cases, which will be visible on click (focus).

To create the input filed border color on focus, we have to use :focus pseudo-class in CSS. The :focus pseudo-class can be used for styling an element that is targeted by the keyboard or the mouse.

In the following example, we will demonstrate how you can change the input field border color on focus. Please have a look over the code example and the steps given below.

HTML

  • In the HTML file, we have 3 elements (one div, two labels, and two inputs). The div element is just a wrapper for the rest of the elements.
  • The label element is used to specify a label for an input field. The value of for attribute is set to the name of the corresponding input field.
  • Both input fields have different class names, which we will use in the stylesheet to change the input field border color on focus.
  • In the head element, we have added a stylesheet style.css using the link element.
<!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>Input field border color change on focus</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div>
        <label for="name">Name:</label>
        <input type="text" class="red"><br><br>
        <label for="email">Email:</label>
        <input type="text" class="green">
    </div>
    
</body>
</html>

CSS

  • We are selecting the div element and setting the value of the text-align property to center. This is required to horizontally center align the input field.
  • We are selecting the first input field using the class name .red with :focus pseudo-class and setting the value of the border property to 5px solid red. As a result, it will change the first input field border color on focus to red.
  • Similarly, we are selecting the second input field using the class name .green with :focus pseudo-class and setting the value of the border property to 5px solid green. As a result, it will change the first input field border color on focus to green.
div {
    text-align: center;
}

.red:focus {
    border: 5px solid red;
}

.green:focus {
    border: 5px solid green;
}