如何使用SCSS访问爷爷元素?

huangapple go评论59阅读模式
英文:

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>

当我在输入字段上聚焦时,我想隐藏标签的第二个元素。我尝试了以下两种方法:

  1. 使用 SCSS:
.input-wrapper {
    $this: parent;

    // ...

    input {
        &amp;:focus {
            parent &gt; label &gt; span:nth-child(2) {
                display: none;
            }
        }
    }
}
  1. 使用CSS:
.input-wrapper {
    // ...

    input:focus {
        .input-wrapper__label &gt; span:nth-child(2) {
            display: none;
        }
    }
}

也许我可以使用if语句来处理label &gt; span:nth-child(2)
英文:

I have a structure like this:

&lt;div class=&quot;input-wrapper&quot;&gt; 
	&lt;input placeholder=&quot;Full name&quot;&gt;
	&lt;label&gt;
		&lt;span&gt;*&lt;/span&gt;
		&lt;span&gt;Full name&lt;/span&gt;
	&lt;/label&gt;
&lt;/div&gt;

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{
		&amp;:focus{
			parent &gt; label &gt; span:nth-child(2){
				display: none;
			}
		}
	}
}


.input-wrapper{
	... 

	input:focus{
		.input-wrapper__label &gt; 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 &gt; 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 &gt; span:nth-child(2){
            display: none;
        }

<!-- language: lang-html -->

&lt;div class=&quot;input-wrapper&quot;&gt; 
	&lt;input placeholder=&quot;Full name&quot;&gt;
	&lt;label&gt;
		&lt;span&gt;*&lt;/span&gt;
		&lt;span&gt;Full name&lt;/span&gt;
	&lt;/label&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 12:39:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定