【问题标题】:CSS3 Centering Image while Rotating旋转时CSS3居中图像
【发布时间】:2014-03-11 22:19:48
【问题描述】:

所以我遇到的基本问题是我想要一个位于各自 div 中间的旋转漩涡。当我尝试在动画之外进行 transform:translate 时,它​​不会被激活,如果我尝试在动画中调用它,图像会围绕左上角旋转。我似乎无法弄清楚如何将图像垂直和水平居中,同时让它旋转。

这是我正在使用的代码:

div img
{
    position: absolute;
    display:block;
    top: 50%;
    left: 50%;

    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -ms-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);

    margin: auto;
    width:auto;
    height: auto;
    max-height: 70%;
    max-width: 70%;




    -webkit-animation: rotate 3s linear infinite 0s;
    -moz-animation: rotateup 3s linear infinite 0s;
    -o-animation: rotate 3s linear infinite 0s;
    -ms-animation: rotate 3s linear infinite 0s;
    animation: rotate 3s linear infinite 0s
}

@-webkit-keyframes rotate {
 from {
     -webkit-transform: rotate(0deg);
}
to {
      -webkit-transform: rotate(360deg);                                 
}

这是一个演示我的问题的小提琴。 http://jsfiddle.net/4j7T4/

感谢大家的帮助!

【问题讨论】:

    标签: html css css-animations css-transforms


    【解决方案1】:

    这是更新后的fiddle

    由于 div 的宽度为 30px,高度为 30px,因此您放置的 margin-left 和 margin-top 为 -15px(或宽度/高度的负一半)

    {
      top: 50%;
      left: 50%;
      margin-top: -15px;
      margin-left: -15px;
    }
    

    另一个只有正方形的例子http://jsfiddle.net/tb5Bg/

    【讨论】:

    • 我知道这对于固定大小的东西是如何工作的,比如我的示例小提琴,但我实际使用的是宽度和高度均为自动的图像,最大为 50%。我尝试使用 margin-top 并保持在 -50% 的位置,但这只是将其返回到顶部和左侧之前的位置。
    【解决方案2】:

    我可能会旋转 div 而不是图像。另外,我会以不同的方式居中。试试这个:你使用的是 sass 还是 autoprefixr?如果没有,你应该检查一下。我正在为.image-w 使用块元素修饰符,这对响应式图像和东西很有用,还有一点@mxin 用于在绝对定位的中心东西上重用。只要您指定要居中的高度和宽度,边距自动就可以解决问题。这里是a codepen.

    HTML

    <div class="image-w spinner"><img src="http://placehold.it/400x400" alt="spinner" /></div>
    

    SCSS

    .image-w {
      //
      img {
        display: block;
        width: 100%;
        height: auto;
      }
    }
    
    @mixin absolute-center {
      position: absolute;
      top: 0; right: 0;
      bottom: 0; left: 0;
      margin: auto;
    }
    
    .spinner {
      width: 10em;
      height: 10em;
      @include absolute-center;
      border-radius: 50%;
      overflow: hidden;
      animation: rotate 3s linear infinite 0s
    }
    
    @keyframes rotate {
      from {
        -webkit-transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(360deg);
      }
      animation: rotate 3s linear infinite 0s
    }
    

    【讨论】:

    • 旋转 div 是我最终所做的,我可能不会想到这一点!谢谢,我会研究一下 sass,看起来它让 css 更友好一些
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2013-03-23
    相关资源
    最近更新 更多