【问题标题】:How can I transform this div without transforming the image within?如何在不转换图像的情况下转换此 div?
【发布时间】:2015-04-10 15:38:32
【问题描述】:

我尝试使用div 制作一个形状并将图像放入其中。我希望图像保持其默认形状(矩形或正方形)而不倾斜,但是当我将图像放入其中时,图像与div 一起倾斜。对于div 形状,我使用的是transform: skewY(-10deg);

.intro {
  width: 180px;
  height: 400px;
  /*	border-radius:50%;*/
  cursor: pointer;
  position: relative;
  background: #fff;
  transform: skewY(-10deg);
  margin: 35px 35px 35px 0px;
}
.intro img {
  width: 100%;
  height: 100%;
}
<div class="intro">
  <img src="http://lorempixel.com/180/400/sports">
</div>

【问题讨论】:

    标签: css css-transforms


    【解决方案1】:

    您正在尝试完成此操作:扭曲外部对象的形状但保持内部形状相同。做到这一点的唯一方法是transform 内部形状由外部形状transform (又名,如果你的skewY(10deg) 在外部形状上,请在skewY(-10deg) 上内部),然后隐藏overflow

    看到这个sn-p:

    .intro {
        width: 180px;
        height: 400px;
        cursor: pointer;
        position: relative;
        background: #fff;
        /* I added the -webkit- prefix as I'm using Safari 8 and
         * it wouldn't show up otherwise. Might want to prefix that! */
        -webkit-transform: skewY(-10deg);
        transform: skewY(-10deg);
        margin: 35px 35px 35px 0px;
        overflow: hidden;
    }
    .intro img {
        width: 100%;
        height: 100%;
        -webkit-transform: skewY(10deg);
        transform: skewY(10deg);
    }
    <div class="intro">
      <img src="http://lorempixel.com/180/400/sports">
    </div>

    这样做的一个恼人的副作用是您的内容似乎被截断了。解决这个问题的唯一方法是使内部形状大于外部形状,从而潜在地填充内部。对于您的图像,我建议:

    .intro { 
        position: relative;
    }
    .intro img {
        /* Use min width and heights higher than 100% 
         * (you might need to experiment here as it depends
         *  on the angle you chose for your skew) to fill
         *  the outer shape completely. */
        min-width: 110%;
        min-height: 110%;
        /* Position the element absolute and 50%
         * from the top and left */
        position: absolute;
        left: 50%;
        top: 50%;
        /* Now add a transform to it to move it with 
         * half of its width and height, therefore centering it. */
        -webkit-transform: skewY(10deg) translate(-50%, -50%);
        transform: skewY(10deg) translate(-50%, -50%);
    }
    

    现在您也可以使用width: 110%; height: 110%; left: -5%; top: -5%;,它会获得类似的结果。玩弄它。

    更新

    根据@vals 的建议,使用scale 转换而不是所有的定位mumbo jumbo 可能要简单得多。它始终是最容易被忽视的最简单的解决方案:

    .intro img {
        -webkit-transform: skewY(10deg) scale(1.2, 1.2);
        transform: skewY(10deg) scale(1.2, 1.2);
    }
    

    【讨论】:

    • 另外,您可以使用缩放解决图像被截断的问题: transform: skewY(10deg) scale(1.1); 用于图像。可能比使用 min-width 等更容易。
    • 更好!我会记住这一点(并在我能/记得的时候修改我的帖子)。
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2011-04-26
    • 2019-12-07
    • 1970-01-01
    • 2021-05-08
    • 2013-05-23
    相关资源
    最近更新 更多