简体   繁体   中英

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. 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.

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.

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

90deg fiddle / 270deg fiddle

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 . 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

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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