how to set border-color of parent elementsame as the color of child element when hover over that child,

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

how to set border-color of parent elementsame as the color of child element when hover over that child,

问题

这是HTML结构的翻译:

<div class="parent">
    <div class="child1" style="background: red;"></div>
    <div class="child2" style="background: blue;"></div>
</div>

要使.parent元素在悬停在.child1上时的边框颜色为红色,在悬停在.child2上时的边框颜色为蓝色,只使用CSS,可以尝试以下代码:

.child1:hover + .parent {
  border-color: red;
}

.child2:hover + .parent {
  border-color: blue;
}

希望这能帮助你实现所需的效果。

英文:

this is structure of html

&lt;div class=&quot;parent&quot;&gt;     
    &lt;div class=&quot;child1&quot; style=&quot;background: red;&quot;&gt;&lt;/div&gt;     
    &lt;div class=&quot;child2&quot; style=&quot;background: blue;&quot;&gt;&lt;/div&gt;  
&lt;/div&gt; 

i want to make border-color of .parent element red when i hover over .child1 and blue when i hover over .child2

using only CSS.

is it possible.


i am new to web, so i ask on chatGPT. it produce some garbage code that didn't work.

.parent:hover {
  border-color: red;
}

.child1:hover ~ .parent {
  border-color: blue;
}

.child2:hover ~ .parent {
  border-color: green;
}

答案1

得分: 2

我终于得到了我的答案。

:has()解决了我的问题。
这是css代码

.parent:has(.child1:hover){
   border-color: red;
}
.parent:has(.child2:hover){
   border-color: blue;
}

这是我正在工作的页面。

codePen链接: https://codepen.io/manoj1310/pen/WNaxRqa

英文:

finally i got my answer.

:has() solved my problem.
here is the css code

.parent:has(.child1:hover){
   border-color: red;
}
.parent:has(.child2:hover){
   border-color: blue;
}

here is the page that i was working on.

codePen: https://codepen.io/manoj1310/pen/WNaxRqa

huangapple
  • 本文由 发表于 2023年4月17日 19:18:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034576.html
匿名

发表评论

匿名网友

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

确定