How to get a css property using css?

32 Views Asked by At

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);
}
2

There are 2 best solutions below

0
dantheman On BEST ANSWER

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>

0
Ganael D On

You're gonna have to use Javascript to dynamically get the border color of the elements. You can add an eventListener of type "mouseover" to every element that has class .hover_effect. Try the following script (that uses jQuery):

$(".hover_effect").on("mouseover", () => {
    // Retrieve the border color
    const borderColor = $(this).css("border-color");

    // Set the outline
    $(this).css("outline", `2px solid ${borderColor}`);
}
);

$(".hover_effect").on("mouseout", () => {
    // Don't forget to cancel the outline when you leave the element
    $(this).css("outline", "none");
}
);

A solution without jQuery would be:

const hoverEffectElements = $(".hover_effect");

  hoverEffectElements.forEach((element) => {
    element.addEventListener('mouseover', () => {
      const borderColor = getComputedStyle(element).borderColor;
      element.style.outline = `2px solid ${borderColor}`;
    });

    element.addEventListener('mouseout', () => {
      element.style.outline = 'none';
    });
  });