Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS :before :after background color

Tags:

css

colors

I want to turn the heart shape black upon click but changing .heart's color won't affect its :before :after selector. Is there any way to do so?

.heart {
  background-color: red;
  height: 60px; /*dimension of the square*/
  position: relative;
  top: 40px; /*position from top*/
  transform: rotate(-45deg); /*negative = counter clockwise, put 0 to try*/
  width: 60px; /*dimension of the square*/
  transition: all 1s ease; /*length of animation*/
}

.heart:before,
.heart:after {
  content:""; /*kosong, for it to exist*/
  background-color: red;
  border-radius: 50%; /*perfect round curve*/
  height: 60px; /*dimension of the shape*/
  position: absolute;
  width: 60px; /*dimension of the shape*/
}

.heart:before {
  top: -30px; /*position of the left shape*/
  left: 0; /*remember rotated ACW 45deg*/
}

.heart:after {
  left: 30px; /*position of the right shape*/
  top: 0px; /*remember rotated ACW 45deg*/
}

.heart
    {
        opacity:0.3; /*original state*/
    }
.heart:hover
    {
        opacity:1; /*hover state*/
    }
.heart:active
    {
        opacity:1; /*hover state*/
        background:black;
    }
like image 782
Nate Avatar asked Jan 23 '17 13:01

Nate


2 Answers

You need to target your pseudo-elements when applying an :active / :hover etc. state as well.

Like so:

.heart:active::before,
.heart:active::after {
  background: black;
} 

Here is a working Fiddle.

I also added a transition for your pseudo elements, so that they can fade nicely with the bottom part of the heart.

like image 118
Tanasos Avatar answered Oct 18 '22 12:10

Tanasos


Simply change the value of the background property of the pseudo-elements to inherit and it will match the backgroundof the parent .heart element at all times. This way you don't have to remember to add more rules if you add more colour changes in the future. And it has the added bonus of inheriting the transition from red to black from the parent.

.heart{
  background:#f00;
  height:60px;
  left:30px;
  opacity:.3;
  position:relative;
  top:40px;
  transform:rotate(-45deg);
  transition:background 1s ease,opacity 1s ease;
  width:60px;
}
.heart:hover{
  opacity:1;
}
.heart:active{
  background:#000;
  opacity:1;
}
.heart:before,.heart:after{
  content:"";
  background:inherit;
  border-radius:50%;
  height:60px;
  position:absolute;
  width:60px;
}
.heart:before{
  left:0;
  top:-30px;
}
.heart:after{
  left:30px;
  top:0;
}
<div class="heart"></div>
like image 34
Shaggy Avatar answered Oct 18 '22 11:10

Shaggy