Search code examples
cssfocus

css focus color overrides background color


I want to "highlight" an element when it's focused.
In this example below if you click on text it also changes background color.

I can't change (add/remove) elements, I can add css class to elements classes only.

Also I don't know what kind of background was applied before (color, gradient, image) and so on.

this is unfocused element
enter image description here

this is result focused state
enter image description here

I'd like add highlight white color with opacity and preserve background color/image/gradient.

expected result:
enter image description here

b {
  background-color: red;
  font-size: 42px;
}

.app-focus:focus {
  background-color: white;
  opacity: 0.1;
}
<b id="id1" class="app-focus" tabIndex="1">text</b>


Solution

  • you have two methods to do it

    1 - Only use opacity in the :focus code.

    .app-focus:focus {
      opacity: 0.8;
    }
    

    2 - Use ::before to make the overlay effect.

    b {
      background-color: red;
      font-size: 42px;
      position: relative;
    }
    
    b::before {
      content: '';
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      background: #fff;
      opacity: 0;
      transition: all .4s;
    }
    
    .app-focus:focus::before {
      opacity: 0.3;
    }
    <b id="id1" class="app-focus" tabIndex="1">text</b>