it is a simple problem but i can't get through it, i am trying to highlight an input box when its focused, but all the div as i styled it differently to add icons inside of it.
here is my code:
input:focus .form-input {
border: 2px solid var(--theme-color);
}
<form>
<div >
<i ></i>
<input type="text" id="username" name="username" placeholder="Enter Your Username"><br>
</div>
<div >
<i ></i>
<input type="password" id="password" name="password" placeholder="Enter Your Password">
</div>
</form>
CodePudding user response:
The element you are trying to style (div.form-input
) is the parent of that input. As far as I know there's currently no way for selecting parent elements based on child state in CSS (or at least not supported by all browsers).
You'd have to rely on js for that:
function highlight(evt) {
// get parent with class .form-input
var parent = evt.target.closest('.form-input');
if (parent) {
if (evt.type === 'focus') {
// add highlight class on focus
parent.classList.add('highlight');
} else {
// remove highlight class on blur
parent.classList.remove('highlight');
}
}
}
// get all inputs of the form
document.querySelectorAll('form input')
.forEach((input) => {
// attach focus and blur events to toggle highlight class
input.addEventListener('focus', highlight, true);
input.addEventListener('blur', highlight, true);
});
.form-input {
display: inline-block;
padding: 5px;
border: 2px solid rgba(0,0,0,.1);
}
.form-input.highlight {
border: 2px solid #000;
}
<form>
<div >
<i ></i>
<input
type="text"
id="username"
name="username"
placeholder="Enter Your Username"
/><br />
</div>
<div >
<i ></i>
<input
type="password"
id="password"
name="password"
placeholder="Enter Your Password"
/>
</div>
</form>
CodePudding user response:
As soon as we have widespread browser support for :has()
, a solution would look like this:
.form-input:has(input:focus) {
border: 2px solid orange;
}
<div >
<input type="text" id="username" name="username" placeholder="Enter Your Username" />
</div>
Currently this is only supported in Safari 15.4 though, but it will soon come to all major browsers.
Until we have that, you can still work with the well-supported :focus-within
pseudo class:
.form-input:focus-within {
border: 2px solid orange;
}
<div >
<input type="text" id="username" name="username" placeholder="Enter Your Username" />
</div>
Please note that this solution comes with the drawback of triggering on any focusable element within div.form-control
. You cannot limit it to certain elements.