Skip to main content

Style Input with Focus

When an input gets focus (is clicked on), some browsers draw a blue outline around it by default. Adding outline: none; to the input turns this off.

When you want your own style on the focused input field, use the :focus selector.

Example

Once a text input is focused, its background color changes.

Prompt
Create an HTML page with a text input field that changes its background color to lightblue when it receives focus, using the CSS :focus selector.
Output: complete HTML page

Example

Once a text input is focused, its border changes.

Prompt
Create an HTML page with a text input field that gets a 3px solid dark border (#555) when it receives focus, using the CSS :focus selector.
Output: complete HTML page

Style Input with icon/image

If an icon should appear within the input, two properties do the work: background-image supplies it and background-position places it. A large left padding then keeps space free for the icon.

Example

Prompt
Create an HTML page with a text input field that has a search icon inside it. Use the background-image property with url('searchicon.png'), position it at 10px 10px, set background-repeat to no-repeat, and add 40px of left padding to make room for the icon.
Output: complete HTML page

Animated Search Input

In this example a search input widens when it gets focus, with the change in width animated by the CSS transition property. That property is covered in more detail later, in the CSS Transitions chapter.

Example

Prompt
Create an HTML page with a search text input that animates its width to 100% when it receives focus. Use the CSS transition property with width 0.4s ease-in-out for a smooth animation effect.
Output: complete HTML page