Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Detect input with valid data not focused with no javascript

Tags:

html

css

I have been checking similar questions in Stackoverflow, but I can't find the proper way to do this:

I want an input without border. When focused, border is blue. Also, when not focused but with text added inside it, border should be blue as well.

I am trying with .Input:focus, .Input:not(:focus):valid {}, with no result: the rule is triggered when the inut is not focused or with text, I add an example:

.Input {
	border: none;
	outline: none;
}
.Input:focus,
.Input:not(:focus):valid {
	border: 2px solid blue;
}
<input class="Input" type="text" name="EMAIL" id="email" placeholder="email">

Any idea will be welcome!


1 Answers

This should work for you:

.Input[value=""], .Input:placeholder-shown {
    border: none;
    outline: none;
}
.Input, .Input:focus {
  border: 2px solid blue;
}

By default, the input field will always have a blue border. The two selectors above it, however, will determine whether to show the border or not.

If the input field has an empty value, or if the placeholder text is displaying, then the border will be removed and the field will have no decoration. Otherwise, if the input doesn't match any of this criteria, it will have a blue border.

The :focus attribute is used to ensure that the field will have a blue border when it is selected but doesn't contain any text, or when it only contains placeholder text.

Hope this helps!

like image 60
Rees Morris Avatar answered Feb 26 '26 13:02

Rees Morris