- toggling styles on label (active/focus) for input field with css only
- 7 Answers 7
- Html
- CSS
- Demo
- Цвет в текстовом поле не меняется после получения фокуса ввода CSS
- Highlight active form with CSS?
- 6 Answers 6
- Option 1 - Forgo the Clickable Submit Button
- Option 2 - Use an Alternate Element to Style the Background
- Option 3 - Use Absolute Positioning to Stack the Elements
- Can you style an active form input's label with just CSS
- 10 Answers 10
toggling styles on label (active/focus) for input field with css only
Wondering whether if there is a css-only way to perform to toggle styles on the corresponding label on input’s focus. So far I have:
$(document).on('focus active', 'input',function()< $('label[for='+$(this).attr('id')+']').addClass('active'); >); $(document).on('blur', 'input',function()< $('label[for='+$(this).attr('id')+']').removeClass('active'); >);
Edit: I am surely aware of the child and sibling selectors «workarounds», but rearranging clean markup for the pure sake of styling seems not right, so if there is another pure css way this answer wins! http://jsfiddle.net/fchWj/3/
7 Answers 7
Try this way:- Place your label after input and float it left. And apply siblings.
Html
CSS
Demo
This is a hack to get the adjacent sibling selector work as it applies only on the following element and not the preceding one. ~ will select all the adjascent siblings after this element. So if you are having different .row for each section of inputs then use + .
If you are willing to switch elements, than here you go
label < float: left; margin-right: 5px; >input[type=text]:focus + label
Explanation: We are using + adjacent selector here, so when the textbox is focused, we select the label tag and apply color red
Note: Don’t forget to clear floats 😉
It’s possible with CSS only, without switching the order of the label and input. You can use a :focus-within CSS pseudo-class on the parent element, which applies to elements, that has a child element with the focus.
In your example, you could use the following:
Note, that this pseudo-class is relatively new, so only modern browsers support it.
There is, but only if you place the label after the input.
input:focus + label
Now if you want the label to be placed before it, then you need to do some css styling with position absolute to place the label before the input field, then add some margin left on the input to move it to the right.
This give you label on top of input, highlight label while input focus.
HTML
.row < display:flex; flex-direction:column-reverse; align-self:flex-start; >.row input:focus < border: 1px solid red; >.row input:focus+label
First we can use a selector that matches a label immediately followed by the input tag (input:focus + label). But there is still the problem, that the label follows after the actual input field. If one would like to have it above the text input we need to switch the positions of the controls. This can be done with a CSS pseudo-table.
The style for the artifical table is.
With this in place we could transform the label e.g. to a table-header-group:
and the input field to a table-row-group:
In combination with our followed by selector we're done and it looks right:
For a demo please see this Fiddle
Цвет в текстовом поле не меняется после получения фокуса ввода CSS
Всем привет! Ребята, пробовал с помощью CSS изменить цвет фона в текстовом поле при фокусе ввода, но что-то ничего не получается. Подскажите, в чём дело? Вот мой html код:
form < input[type="text"], textarea, ::-webkit-input-placeholder, textarea::-webkit-input-placeholder < font-size: 1.125em; line-height: 1; color: $formSeactionCommonColor; font-family: "Titillium Web", Roboto, Arial, sans-serif !important; background-color: #273a71; border: none; border-radius: 5px; padding: 15px; >::-webkit-input-placeholder::after, textarea::-webkit-input-placeholder::after < content: ' \002A'; color: #db424b; padding: 15px; padding-left: 5px; >.text-dataes < @include flex_row_wrap; justify-content: space-around; @include small < display: inline-block; >@include extra-small < display: inline-block; >input[type="text"] < width: 45%; @include small < width: 100%; margin-bottom: 20px; >@include extra-small < width: 100%; margin-bottom: 20px; >> textarea < width: 95%; margin-top: 27px; margin-bottom: 60px; @include small < width: 100%; margin-top: 0; margin-bottom: 20px; >@include extra-small < width: 100%; margin-top: 0; margin-bottom: 20px; >> input[type="text"]:focus::-webkit-input-placeholder, textarea:focus::-webkit-input-placeholder < color: transparent; >input[type="text"]:focus, textarea:focus < border: 2px solid #ffdd99; background-color: #a75978; >> input[type="submit"] < @include centerUppercase; background-color: #30bae7; color: $formSeactionCommonColor; border: none; transition-duration: 1s; align-items: center; white-space: normal; word-wrap: break-word; &:hover < background-color: #a75978; box-shadow: -4px 4px 20px #000; cursor: pointer; >> >
Highlight active form with CSS?
This obviously doesn't work, as is why I'm asking the question. How can I get the form which has one if it's inputs as the focus to highlight? That is, I want to be able to apply styles to the active FORM, not the active INPUT - is that doable without JS or something?
That's is the big one. If you have multiple forms in the page, without JS, the renderer will not be able to link the stylesheet and the form. The best way to do it is to have the form name/ID and have JavaScript to apply the stylesheet when form get focus.
I don't know of any method to do it without JavaScript, but it's not too hard with JavaScript/jQuery: jsfiddle.net/3mCwg. Is there a particular reason why you want to use CSS only?
Damn I was hoping that wouldn't be the case 🙁 It's weird though because form:hover and form:active work (I get why hover would, but active?)
6 Answers 6
This is an older question, but as of now, some of the more popular browsers are supporting a css pseudo selector called :focus-within , which can style a form (without javascript) that has a focused input.
Here is the current support for the selector: http://caniuse.com/#search=focus-within
If you're using a supported browser, here is an example: https://codepen.io/jumprope-design/pen/LjxORX
This code works as an exercise but probably not a solution you should use . The version relying on legend actually seems acceptable.
There is no form:focus selector so I thought instead the individual input:focus could create the desired effect using pseudo-elements. However, pseudo-elements can only be used on elements with content, like if I were to replace input[type=submit] with button
form < position:relative; >/*style the pseudo-element before a button that is a general sibling of any element that currently has focus within a form*/ form *:focus~button:before < content:"";display:block;background:red; /*take up the entire space of the form*/ position:absolute;top:0;right:0;bottom:0;left:0; /*but render behind its children*/ z-index:-1; >
Fiddled, but it instantly looked pretty crazy, so I've refactored the solution to rely onto a legend element. Enjoy 🙂
That's very fascinating, it's got a few issues but in essence answers the question with pure CSS (and a legend)! Very innovative, thanks a lot for this
My kneejerk was that child selectors tend to behave funky in IE and honestly I had never seen the sibling selector before. Had to google it. You're right though the pseudo-elements might be more of a problem than the ~. Thanks for the tip!
There is no parent selector in CSS so javascript is required. CSS 4 is planned to get this feature, however.
I've been looking for the same styling technique for a while. From a UI/UX standpoint - simplifying search forms to a single element makes a lot of sense in certain situations.
Consider the example below:
When you approach it from a development standpoint the knee-jerk is to decide to style the form itself instead of the input elements. A transparent input[type=text] to the left, and a transparent .PNG submit button to the right and you've got a sharp looking search field.
As you've discovered though, you give up the CSS style capabilities associated with :focus because the input field isn't the one controlling the background / color etc - the form element is instead.
The form:focus selector would be a perfect way to handle that. Unfortunately, we've got to wait to CSS4 for that (thanks to matt3141 for the tid-bit).
In the meantime, you have a few options available
Option 1 - Forgo the Clickable Submit Button
I usually try and avoid this if possible, but you have the option to forgo the submit button altogether. Style the text field as you intended, and use a background image with the position limited to the left or of the field right. When the user types in their query, and presses enter, you can still fire a GET action. The example image above uses this technique.
Drawbacks: Users who still click search buttons might be confused.
Option 2 - Use an Alternate Element to Style the Background
Your next option is to take advantage of the sibling selector and content tags as o.v. has so generously explained in his/her previous answer. This in effects adds a new element and styles it to act as a new background for a specified area when the :focus effect is applied to an input field.
Pros: Extendable to larger forms with multiple fields more easily.
Drawbacks: The intensive selectors may not degrade as gracefully as we'd like.
Option 3 - Use Absolute Positioning to Stack the Elements
In situations where the text field will encompass the full width of the form, you can use a the position:absolute; attribute to simply load the submit button over top of the input element, and then a few css tweaks on the button to remove the background / border - giving the same effect as our example image above, but with added benefit of making it clickable.
Step One: Give the form a position - relative/absolute/fixed.
Step Two: Give the text field a width of 100%.
Step Three: Give the button an absolute position, and right position of 0.
I've updated o.v.'s fiddle to incorporate the new technique:
Pro's: Degrades gracefully, gives us what we want in most single input field cases.
Drawbacks: Not as easily extendable to large forms like o.v.'s fix is.
As you can see, each option has its own drawbacks - but if you know about them ahead of you can usually lessen their impact. Hope this helps!
Can you style an active form input's label with just CSS
You can give the label an id or class and target it in your css. Or are you asking if you can style it without changing the markup and adding an id or class?
10 Answers 10
No. there is unfortunately no predecessor selector in css
having the label after the input would be dooable:
you could use some positioning to display before.
thanks, i thought this might be the case. would be really nice. unfortunately i can't change the markup :o( i'll keep this in mind for the future though.
For completeness, if your input field is within the label you can use focus-within:
@alexbooots No this shoudn't be. Implicit Label aren't recommended. Here is a small article you can read
Make sure you check the draft as this may change: https://drafts.csswg.org/selectors-4/#relational
The :has() relational pseudo-class will allow the selection of parents for example, the following selector matches only elements that contain an child:
This can be combined with other selectors such as :focus , :active or :not to offer a lot of potential.
Unfortunately browser support isn’t great at the time of writing: https://caniuse.com/#feat=css-has
Adding this for people finding this page in the future. CSS4 will have a parent selector allowing you to choose what element to apply the style to:
I think the current spec allows you to specify which item is matched with a ! sign - the subject selector.
This allows far greater control than just parent, for example in this scary chain below the p tag is the target!
article > h1 + section > p! > b > a