html - On hover of child, change background color of parent container (CSS only) -


this common question. gets closed duplicate of question: is there css parent selector?

the duplicate job pointing out parent elements cannot targeted css. provides little no guidance original question, may caught in xy problem.

in particular case...

how can background color of parent changed when hovering child?

...there @ least 1 css solution may solve problem.

<div>    <a href="#">anchor text</a>  </div>

although can't select parent elements css, may able accomplish task method.

you want background color of parent change when child hovered.

consider using spread-radius value of css box-shadow property.

by creating huge spread radius, can change color of surrounding area (which no different visually parent element).

div {      overflow: hidden;              /* 1 */  }    a:hover {      box-shadow: 0 0 0 1000px red;  /* 2 */  }    /* non-essential decorative styles */  div {     height: 150px;    width: 150px;    border: 1px dashed black;    display: flex;    justify-content: center;     align-items: center;  }
<div>    <a href="http://www.stackoverflow.com/">anchor text</a>  </div>

notes:

  1. overflow: hidden limit child's box shadow
  2. the box-shadow values follows:

<box-shadow> : <offset-x> <offset-y> <blur-radius> <spread-radius> <color>

  • offset-x ~ horizontal distance element
  • offset-y ~ vertical distance element
  • blur-radius ~ makes shadow increasingly bigger , transparent
  • spread-radius ~ makes shadow expand (without fading)

in case, first 3 values don't matter.

what need spread-radius grow lot, have clipped container overflow: hidden.


and if there's element in container?

<div>   <h2>hello</h2>   <a href="http://www.google.com">anchor text</a> </div> 

div {      overflow: hidden;  }  a:hover {      box-shadow: 0 0 0 1000px red;  }  div {     height: 150px;    width: 150px;    border: 1px dashed black;    display: flex;    flex-direction: column;    justify-content: center;     align-items: center;  }
<div>    <h2>hello</h2>    <a href="http://www.stackoverflow.com/">anchor text</a>  </div>

you can apply z-index sibling.

h2 { z-index: 1; } 

and, because elements happen in flex container in example, they don't need positioned z-index work.

h2 { z-index: 1; }    div {      overflow: hidden;  }  a:hover {      box-shadow: 0 0 0 1000px red;  }  div {     height: 150px;    width: 150px;    border: 1px dashed black;    display: flex;    flex-direction: column;    justify-content: center;     align-items: center;  }
<div>    <h2>hello</h2>    <a href="http://www.stackoverflow.com/">anchor text</a>  </div>


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -