Ammar Ahmed Ammar Ahmed - 6 months ago 8
CSS Question

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>




Answer

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>

Comments