Search code examples
htmlcssanimationwebkit

How can i make a css animation only apply to the image and not its border?


I'm using this question format to hopefully make it easier to understand :)

Problem:

I want to make an image spin, but I want its border not to spin with it. It will look like an image is spinning in a still white frame.

Attempted code:

#skin3{
 position: relative;
 top: -71px;
 left: 115px;
 width: 95px;
 height: 100px;
 border: 2px solid white;
 padding: 5px;
 padding-right: 8px;
 padding-top: 15px;
 padding-bottom: 15px;
 cursor: pointer !important;
 margin-bottom: -160px;
 -webkit-animation:spin 4s linear infinite;
-moz-animation:spin 4s linear infinite;
animation:spin 4s linear infinite;
}

@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }

This is the css. Where it says, border: 2px solid white; it defines the border. This css spins the image and its border.

Html:

  <img src="../images/skins/skin3white.png" id="skin3" onclick="changeskin3(); location.href='profile.php'" action="changeskin3.php"/>

I don't know why this matters, but it might help :)

Conclusion:

I don't want to create a separate border with a div or something, so hopefully this is possible.

I've just started using animations, and i'm still learning. Thanks for helping!


Solution

  • What you're asking for isn't possible by design. CSS is a box model system meaning each element is given a box to render in. That box has a content, padding, border, margin and outline. The moment you shift that box in any direction (e.g. transform), the whole box moves. Think of it literally like a shipping box as it has contents and a border (the actual cardboard). You can't rotate the contents of that box without rotating the whole box.

    Now you could take a proverbial box-cutter to that shipping box and render the whole thing in a canvas and program the whole thing yourself. But honestly, that's overkill.

    Instead, it's better to just put a box inside the box and spin the inner box and let the outer box not move. As @garr-godfrey commented, you know the solution, to use a second div.