0

I need your help.

Is there a way to change the border color of the parent div, when the child select box is either hovered, active or focused?

<style type="text/css">

div.select select:hover,
div.select select:focus,
div.select select:active {
   background: rgb(255,255,196);
   border-color: rgb(85,85,85);
}

</style>

<div class="select" style="background: #FFF; width: 200px; border: 1px solid rgb(170,170,170);">
  <select style="width: 100%; border:0px; outline:0px; padding: 2px;">
    <option value="Sal">Sal</option>
    <option value="Awesome">Awesome!</option>
  </select>
</div>
BobbyJones
  • 1,251
  • 1
  • 16
  • 37
  • 1
    there is no way to traverse up the DOM tree, something like this would need to be done in javascript – Curt Husting Jan 19 '18 at 19:44
  • 1
    Possible duplicate of [Is there a CSS parent selector?](https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector) – connexo Jan 19 '18 at 19:46

2 Answers2

0

As we know, there is no CSS parent selector, but if all you need to do is change border-color (and possibly background) on :hover, you can use a pseudo element & some positioning + z-index hacks to do it. Here's an example with comments inline

div.select {
  height: 50px;
  background: #FFF;
  width: 200px;
  position: relative;
  /* to position the pseudo element */
  z-index: 1;
  /* HACK: to make sure it doesn't affect anything globally. */
  /* Increase this value if the element is not visible */
  /* or you have z-index set in your code */
}

.select-wrap::after {
  content: ' ';
  position: absolute;
  top: -1px;
  /* for outside border */
  left: -1px;
  right: -1px;
  bottom: -1px;
  background: #eee;
  border: 1px solid transparent;
  pointer-events: none;
  /* to make sure hovering on the background doesn't trigger color change */
}

.select-wrap:hover::after {
  background: yellow;
  border-color: black;
}

select {
  width: 100%;
  border: 0px;
  outline: 0px;
  padding: 2px;
  position: relative;
  z-index: 10; 
  /* HACK: Can be any number more than the :after element's z-index. */
  /* As the parent has a z-index, it won't affect anything globally */
}
<div class="select" style="">
  <div class='select-wrap'>
    <select>
    <option value="Sal">Sal</option>
    <option value="Awesome">Awesome!</option>
  </select>
  </div>
</div>

Codepen link: https://codepen.io/palash/pen/wpRVQV

Also, note that pseudo elements do not work with <select>, hence the need for the 'select-wrap' <span>

Palash Karia
  • 572
  • 3
  • 10
0

An alternative solution would be to use the focus-within selector: https://css-tricks.com/almanac/selectors/f/focus-within/

famouspotatoes
  • 899
  • 10
  • 21