简体   繁体   English

如何在容器内定位旋转图像?

[英]How can I position a rotated image within a container?

Using CSS3, HTML (and javascript/jquery if needed), I need to rotate an image 90/270 degrees and have it position to fill its parent div/container. 使用CSS3,HTML(以及javascript / jquery,如果需要),我需要将图像旋转90/270度并使其位置填充其父div /容器。 Sounds simple, but when images are rotated, there positioning changes and I can't figure out how or why. 听起来很简单,但是当图像旋转时,定位发生变化,我无法弄清楚如何或为什么。

Here is a jsFiddle to explain - http://jsfiddle.net/UPGkU/2/ - I just want the blue logo to be position exactly within the red div. 这是一个jsFiddle来解释 - http://jsfiddle.net/UPGkU/2/ - 我只是希望蓝色标志位于红色div内。

Of course, I could use specific offsets, but if a different image is used, those offsets change, so I really want to find a generic solution. 当然,我可以使用特定的偏移,但如果使用不同的图像,那些偏移会改变,所以我真的想找到一个通用的解决方案。

Any help would be fantastic, thanks! 任何帮助都会很棒,谢谢!

You need to set a transform-origin - in this scenario, a point around which the image gets rotated. 您需要设置transform-origin - 在此场景中,图像旋转的点。

#image {
  -webkit-transform: rotate(90deg);
  -webkit-transform-origin: 0 0; //initially 50% 50%
  margin-left: 100%;
}

90deg fiddle / 270deg fiddle 90度小提琴 / 270度小提琴

Update: 更新:

The challenge with the latter is that we can't really modify transform-origin as its position is relative to the not yet transformed element and we can't just set margin-top:100% since margin values (even vertical ones) are calculated as a percentage always relative to the width of the containing block . 后者面临的挑战是我们无法真正修改transform-origin因为它的位置相对于尚未变换的元素而且我们不能只设置margin-top:100%因为计算了边际值(甚至是垂直值) 总是相对于包含块的宽度的百分比 The following code should work: 以下代码应该有效:

#image {
  -webkit-transform: rotate(-90deg);
  -webkit-transform-origin: 0 0;
  position:relative;
  top:100%;
}

try with 尝试

#image {
    -webkit-transform: rotate(90deg);
    -webkit-transform-origin: 0 100%;
    position : relative;
    top      : -50px;
}

Hi now used to this css used position 嗨现在习惯了这个css使用的位置

#wrapper {
    width:50px;
    height:150px;
    border:2px solid red;
    position:relative;
}
#image {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    position:absolute;
    left:-49px;
    top:50px;
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM