Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if input has text/value with CSS

Tags:

html

css

input

I've looked around a bit but can only find JS solutions to this.

Is there a way with CSS to detect if an input has any text entered?

What I'm doing is basically this (cut out the irrelevant code for this question):

 .search-form input[type="text"] {
    width: 0 !important;
}
.search-form input[type="text"]:focus {
    width: 100% !important;
}

Essentially, clicking on the label expands the input to 100% of the page width. This works fine, but when you enter text and click off the input, it shrinks back to width:0 - therefore hiding the inputted text. Is there a way with CSS to prevent this behaviour and keep it at width:100% like when the input is :focus when there's text inputted?

like image 333
LT86 Avatar asked Oct 21 '25 00:10

LT86


2 Answers

Try adding the "required" property to the text field in the HTML, and then add this to the CSS:

.search-form input[type="text"]:valid {
    width: 100% !important;
}

I would probably try to avoid all those !importants though.

like image 159
Dave 5000 Avatar answered Oct 23 '25 16:10

Dave 5000


Not sure if it will work for your specific use case, but you could achieve the effect with a fake input, using contenteditable

Working Example

 .fakeInput {
     border: 1px solid red;
     display:inline;
     padding:2px; /* optional */
 }
 .fakeInput:focus {
     display:block;
     border: 2px solid blue;
     width:100%;
     height:1em;
 }

<div class="search-form">
    <div class="fakeInput" contenteditable="true"></div>
</div>
like image 40
apaul Avatar answered Oct 23 '25 14:10

apaul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!