简体   繁体   中英

how to select a sibling element when hovering in CSS?

I can't seem to figure out how to to get the rect element to change color to purple when the text is highlighted. Instead, only the text color is changing. Is there is a way to do this using CSS only?

Rect should change it's color to purple when the text is hovered over.

 .chart rect { //fill: steelblue; stroke: black; } .x.axis path { display: none; } text { text-anchor: middle; alignment-baseline="middle"; } rect:hover { fill: purple; } rect ~ text:hover { fill: purple } 
 <svg class="chart" width="800" height="60"> <g transform="translate(108.2258064516129,30)"> <rect width="206.4516129032258" height="29" fill="orange"></rect> <text x="103.2258064516129" y="15" dy=".35em">ABB vs BBA</text> <text x="103.2258064516129" y="-20" dy=".35em" style="fill: black;">Round 2</text> </g> </svg> 

Instead of fill here:

rect ~ text:hover {
  fill: purple;
}

… use pointer-events: none :

rect ~ text {
  pointer-events: none;
}

That will keep the focus within the rectangle even when the mouse is over the text.

Snippet:

 .chart rect { //fill: steelblue; stroke: black; } .x.axis path { display: none; } text { text-anchor: middle; alignment-baseline="middle"; } rect:hover { fill: purple; } rect ~ text { pointer-events: none; } 
 <svg class="chart" width="800" height="60"> <g transform="translate(108.2258064516129,30)"> <rect width="206.4516129032258" height="29" fill="orange"></rect> <text x="103.2258064516129" y="15" dy=".35em">ABB vs BBA</text> <text x="103.2258064516129" y="-20" dy=".35em" style="fill: black;">Round 2</text> </g> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM