sazr
sazr

Reputation: 25928

Change Colour Opacity When Dont know RGB values only Alpha

I am attempting to change a buttons colour to 50% opacity when hovered over. This is simple enough when I know what the colour is but it will change at runtime.

Any ideas how I can do this with CSS3? I know I could do this easily with LESS but its not available to me.

.my-btn {
    background-color: rgba(255,0,0,1); /* Will change at run time to anything */
}

.my-btn:hover {
    background-color: rgba(?,?,?,0.5); /* I dont know what the rgb values will be */
}

Upvotes: 2

Views: 513

Answers (3)

misterManSam
misterManSam

Reputation: 24692

Problem

Using the opacity property on the button itself would affect the text of the button; not ideal.

Solution

Apply the background color to a pseudo-element instead and layer it underneath the text with negative z-index. When needed, use the opacity property on the pseudo-element to create your transparent background.

Example

Note: Pseudo-elements cannot be applied to the <input> element as it cannot have children. This will only work with elements that can have children, such as <button> and <a>.

button {
  position: relative;
  background: none;
  border: solid 1px #EEE;
  padding: 10px;
  border-radius: 5px;
  overflow: hidden;
}
button:before {
  content: '';
  position: absolute;
  top: -1px;
  right: -1px;
  bottom: -1px;
  left: -1px;
  background: red;
  z-index: -1;
  opacity: .5;
}
button:hover:before {
  opacity: .8;
}
button:active:before {
  background: orange;
}
<button>Button</button>

Upvotes: 3

partypete25
partypete25

Reputation: 4413

It's a bit tricky because using a combination of a rgb background color and opacity sounds like it will work but the opacity will apply to everything inside the element - including the text. there are a number of ways of getting around this though so use a solution that will work for your situation.

Essentially you've got to separate the background element from the rest of the button so that only the background color gets effected by the opacity change on hover.

.my-btn:hover a {
  background-color: rgb(255,0,0);
  opacity:.5;
}
<div class="my-btn">
  <span aria-hidden="true">whatever</span>
  <a href="#"><span class="sr-only">whatever</span></a>
</div>

Here's a demo

Upvotes: 1

A.J. Uppal
A.J. Uppal

Reputation: 19264

Use the opacity attribute:

.my-btn:hover {
   opacity: 0;
}

.my-btn:hover {
  opacity: 0;
  }
<input class="my-btn" type="submit"></input>

Upvotes: 0

Related Questions