CSS样式在:hover状态下应用到另一个元素

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

CSS style on :hover to another element

问题

当我悬停在<li>上时,我如何选择我的<a>元素?

<a href="#">Link</a>
<ul>
  <li>Element 1</li>
  <li>Element 2</li>
</ul>
a ul:hover {
  color: red;
}
英文:

How when I hover on the &lt;li&gt;I can select my &lt;a&gt;element ?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

a ul:hover {
  color: red;
}

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

&lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt;
&lt;ul&gt;
  &lt;li&gt;Element 1&lt;/li&gt;
  &lt;li&gt;Element 2&lt;/li&gt;
&lt;/ul&gt;

<!-- end snippet -->

答案1

得分: 1

你可以使用 :has 来实现,代码如下:

a:has(+ ul:hover) {
  color: red;
}

这段代码会选中包含在链接后的 ul 元素在悬停状态下的情况。

英文:

You can do this using :has like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-css -->

a:has(+ ul:hover) {
  color: red;
}

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

&lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt;
&lt;ul&gt;
  &lt;li&gt;Element 1&lt;/li&gt;
  &lt;li&gt;Element 2&lt;/li&gt;
&lt;/ul&gt;

<!-- end snippet -->

答案2

得分: 0

Sure, here is the translated code portion:

对于那些支持 :has 选择器的浏览器,您可以使用:

<style>
  a:has(+ ul li:hover) {
    background: red;
  }
</style>
<a href="#">链接</a>
<ul>
  <li>元素 1</li>
  <li>元素 2</li>
</ul>

请注意,在 caniuse.com 上检查是否有足够的支持适用于您的情况 - Edge/Chrome/Safari 支持它,但 Firefox 需要设置一个标志。

英文:

For those browsers which support :has you can use:

<!-- begin snippet: js hide: false console: true babel: false -->

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

&lt;style&gt;
  a:has(+ ul li:hover) {
    background: red;
  }
&lt;/style&gt;
&lt;a href=&quot;#&quot;&gt;Link&lt;/a&gt;
&lt;ul&gt;
  &lt;li&gt;Element 1&lt;/li&gt;
  &lt;li&gt;Element 2&lt;/li&gt;
&lt;/ul&gt;

<!-- end snippet -->

However, check on caniuse.com that there is enough support for your use case - Edge/Chrome/Safari support it but Firefox requires a flag to be set.

huangapple
  • 本文由 发表于 2023年4月20日 02:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76057571.html
匿名

发表评论

匿名网友

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

确定