[英]how can i select the sibling ::after pseudo element when input:focus
I want to make a simple input that when you focus on it a nice border appears from the bottom center of it with some transition:我想做一个简单的输入,当你专注于它时,一个漂亮的边框会从它的底部中心出现一些过渡:
<form method="POST" action="/admin/add-product" class="add-product">
<div class="form-input">
<label for="title">title</label>
<input type="text" name="title" id="title" placeholder="title">
</div>
<button className="btn btn-green">Add product</button>
</form>
\* some basic styling for the form *\
.add-product {
width: 500px;
max-width: 95%;
margin: 3rem auto;
padding: 2rem;
}
\* .form-input contains the input and the label *\
.form-input {
width: 100%;
position: relative;
}
.form-input input,
.form-input label {
display: block;
width: 100%;
margin-bottom: 1rem;
}
.form-input input {
height: 2rem;
background: transparent;
border: transparent;
}
\* the ::after *\
.form-input::after {
content: "";
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
height: 2px;
width: 0%;
background-color: var(--green);
transition: width 0.6s;
}
\* this where I think I made a mistake these changes are not applied to ::after at :focus *\
.form-input input:focus + ::after {
width: 100%;
}
I expected to see the::after element's width to change but it doesn't so I think there is a mistake in selecting this way.form-input input:focus +::after;我希望看到 ::after 元素的宽度发生变化,但事实并非如此,所以我认为选择这种方式是错误的。form-input input:focus +::after; even though I think there is no尽管我认为没有
CSS does have a :focus-within
pseudo class solution for this: CSS 确实有一个:focus-within
pseudo class 解决方案:
.form-input:focus-within::after { width: 100%; }
.form-input::after
matches the pseudo-element that appears after the content of any .form-input
element. .form-input::after
匹配出现在任何.form-input
元素内容.form-input::after
的伪元素。
.form-input input:focus + ::after
matches the pseudo-element that appears after the content of the next sibling of any focused input that is a descendant of .form-input
. .form-input input:focus + ::after
匹配出现在.form-input
后代的任何有焦点输入的下一个同级内容之后出现的伪元素。
Unless you have HTML like: 除非您有类似HTML的代码:
<div class="form-input">
<input>
<div class="form-input"></div>
</div>
… that isn't going to match anything. ……那将不会匹配任何东西。
You can't select the parent element's ::after
based on the focus state of a child element. 您不能基于子元素的焦点状态来选择父元素的::after
。 CSS doesn't have a parent selector . CSS没有父选择器 。
You'd need to use JS for this. 您需要为此使用JS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.