4

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?

6
  • Is there any reason to why you cant use JS? Commented May 22, 2014 at 21:11
  • Provide us a Fiddle so we can help you a bit more Commented May 22, 2014 at 21:11
  • Pretty sure you need JS for this, CSS use logic or have conditionals so without that I don't see any way of doing this. Commented May 22, 2014 at 21:12
  • @KM123, no not really, I was just trying to work out the most lightweight option and thought there might be some kind of selector or workaround for this. Thanks anyway. Commented May 22, 2014 at 21:12
  • 1
    I would seriously consider using a light framework like jQuery. Would you like me to provide you the code to acheive what you want? Commented May 22, 2014 at 21:13

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I was thinking this could work, and built a fiddle to try it after you posted.
This is just beautiful!
And what if you would like submit form and element must be optional?? This will not working... (jQuery validate do not submit form...)
must be a better way than valid
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.