【问题标题】:Changing the border color of parent div when the child select is hovered, active, focused当子选择为悬停,活动,焦点时更改父div的边框颜色
【发布时间】:2018-06-29 02:48:59
【问题描述】:

我需要你的帮助。

当子选择框悬停、活动或聚焦时,有没有办法改变父 div 的边框颜色?

<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>

【问题讨论】:

标签: html css


【解决方案1】:

正如我们所知,there is no CSS parent selector,但如果您需要做的只是更改 :hover 上的 border-color(可能还有 background),您可以使用伪元素和一些定位 + z-index hacks做。这是一个内联 cmets 的示例

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 链接:https://codepen.io/palash/pen/wpRVQV

另外,请注意pseudo elements do not work with &lt;select&gt;,因此需要“选择包装”&lt;span&gt;

【讨论】:

    【解决方案2】:

    另一种解决方案是使用focus-within 选择器:https://css-tricks.com/almanac/selectors/f/focus-within/

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2018-08-11
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      相关资源
      最近更新 更多