cssborderattroutline

How to get a css property using css?


What I want is when an element has the class hover_effect, there will be a two pixel outline with the same color as the border whenever you hover over it. As you can see in the code below. The problem is that I don't think the attr() function can pick up css functions that was declared earlier in the same file.

button {
  border: 1px solid green;
}

.hover_effect:hover {
  outline: 2px solid attr(border-color);
}

Solution

  • Yeah that's not what attr() is used for. You could use a css variable for this instead:

    button {
      border: 1px solid var(--borderColor);
    }
    
    button.green {
      --borderColor: green;
    }
    
    button.blue {
      --borderColor: blue;
    }
    
    button.red {
      --borderColor: red;
    }
    
    .hover_effect:hover {
      outline: 2px solid var(--borderColor);
    }
    <button class="green hover_effect">Button</button>
    
    <button class="blue hover_effect">Button</button>
    
    <button class="red hover_effect">Button</button>

    You could also potentially use currentColor, but that means the text of the button would be the same as the border color.

    button {
      color: blue;
    }
    
    .hover__effect:hover {
      outline: 2px solid currentColor;
    }
    <button class="hover__effect">Button</button>