英文:
How can I access the grandparent element with SCSS?
问题
<div class="input-wrapper">
<input placeholder="Full name">
<label>
<span>*</span>
<span>Full name</span>
</label>
</div>
当我在输入字段上聚焦时,我想隐藏标签的第二个元素。我尝试了以下两种方法:
- 使用 SCSS:
.input-wrapper {
$this: parent;
// ...
input {
&:focus {
parent > label > span:nth-child(2) {
display: none;
}
}
}
}
- 使用CSS:
.input-wrapper {
// ...
input:focus {
.input-wrapper__label > span:nth-child(2) {
display: none;
}
}
}
也许我可以使用if语句来处理label > span:nth-child(2)吗?
英文:
I have a structure like this:
<div class="input-wrapper">
<input placeholder="Full name">
<label>
<span>*</span>
<span>Full name</span>
</label>
</div>
I want to hide the second span of the label with SCSS, when I do a focus on input field.
I tried to:
.input-wrapper{
$this: parent;
...
input{
&:focus{
parent > label > span:nth-child(2){
display: none;
}
}
}
}
.input-wrapper{
...
input:focus{
.input-wrapper__label > span:nth-child(2){
display: none;
}
}
}
Maybe I could do something with label > span:nth-child(2) with if?
答案1
得分: 1
为了实现预期的结果,您可以使用相邻兄弟选择器(+)来针对输入焦点上的标签使用以下选项:
input:focus + label > span:nth-child(2)
以下是示例代码和代码示例的链接 - https://codepen.io/nagasai/pen/PoBLBBm 供参考
<!-- language: lang-css -->
input:focus + label > span:nth-child(2){
display: none;
}
<!-- language: lang-html -->
<div class="input-wrapper">
<input placeholder="Full name">
<label>
<span>*</span>
<span>Full name</span>
</label>
</div>
注意:上述代码片段中的HTML和CSS仅用于示例目的。
英文:
To achieve expected result, you can use below option of adjacent sibling selector(+) of targeting label on input focus
input:focus + label > span:nth-child(2)
Sample code below and codepen - https://codepen.io/nagasai/pen/PoBLBBm for reference
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
input:focus + label > span:nth-child(2){
display: none;
}
<!-- language: lang-html -->
<div class="input-wrapper">
<input placeholder="Full name">
<label>
<span>*</span>
<span>Full name</span>
</label>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论