Keep box-shadow direction consistent while rotating

后端 未结 3 1087
长发绾君心
长发绾君心 2020-12-03 10:43

When giving e.g. a

a box-shadow as well as rotating it will cause a rotation of the box-shadow direction - which is problematic when the box-shadow
3条回答
  •  感动是毒
    2020-12-03 11:26

    Keeping direction of an offset box-shadow consistent during rotation is simple with CSS transforms.
    This approach relies on the fact that the transform origin is moved with the transforms. This means that when several transforms are set on the same element, the coordinate system of each transform changes according to the previous ones.

    In the following example, the blue element is a pseudo element and the shadow is the div element:

    div {
      width: 40px; height: 40px;
      margin: 40px;
      box-shadow: 0px 0px 10px 5px #000;
      animation: spinShadow 2s infinite;
      background-color: #000;
    }
    @keyframes spinShadow {
      to { transform: rotate(360deg); }
    }
    div:before {
      content: '';
      position: absolute;
      left:-5px; top:-5px;
      width: 50px; height: 50px;
      transform: rotate(0deg) translate(-10px, -10px) rotate(0deg);
      animation:inherit;
      animation-name: spinElt;
      background-color: #0bb;
    }
    @keyframes spinElt {
      to { transform: rotate(-360deg) translate(-10px, -10px) rotate(360deg); }
    }

    Explanation of the transition property on the pseudo element (See the following code snippet for an illustration of the steps):

    transform: rotate(-360deg) translate(-10px, -10px) rotate(360deg)
    
    1. rotate(-360deg) counters the rotation of the parent to make the pseudo element static.
    2. translate(-10px, -10px) the pseudo element is translated to make the shadow offset
    3. rotate(360deg) the pseudo element is rotated in the same direction as parent

    div {
      width: 40px; height: 40px;
      margin: 40px;
      box-shadow: 0px 0px 10px 5px #000;
      animation: spinShadow 2s infinite;
      background-color: #000;
    }
    @keyframes spinShadow {
      to { transform: rotate(360deg); }
    }
    div:before {
      content: '';
      position: absolute;
      left:-5px; top:-5px;
      width: 50px; height: 50px;
      animation:inherit;
      background-color: #0bb;
    }
    #first:before{
      transform: rotate(0deg);
      animation-name: first;
    }  
    @keyframes first {
      to { transform: rotate(-360deg); }
    }
    #second:before{
      transform: rotate(0deg) translate(-10px, -10px);
      animation-name: second;
    }  
    @keyframes second {
      to { transform: rotate(-360deg) translate(-10px, -10px); }
    }
    #complete:before{
      transform: rotate(0deg) translate(-10px, -10px) rotate(0deg);
      animation-name: complete;
    }  
    @keyframes complete {
      to { transform: rotate(-360deg) translate(-10px, -10px) rotate(360deg); }
    }
    1. Counter rotate:
    2. Translate :
    3. Rotate:

提交回复
热议问题