简体   繁体   中英

Centering an image with absolute position (top, left)

I am using parametric equations to position images around a circle ( How do I calculate a point on a circle's circumference? )

I am doing this in less, using simple math:

// x,y position on circumference:
// x = a + r * cos(t)
// y = b + r * sin(t)

.position {
left: @a + ( @r *  cos(@t) );
top: @b + ( @r *  sin(@t) );
}

The trouble I have is that this positions the image by the top left corner, not the center of the image, so doesn't account for the visual offset of height and width this has. Trying to adjust by height/2, width/2 doesn't work as the angle of each image is different.

Is there an easy way to position an image this way so it is centred on x,y?

.position {
    left: @a + ( @r *  cos(@t) );
    top: @b + ( @r *  sin(@t) );

    margin-left: -@r;
    margin-top: -@r;
}

Instead of calculations you simply could have done this though:

top:50%;
left:50%; 
position:absolute; 

margin-left:-@r;
margin-top:-@r;

FIDDLE DEMO

Subtracting Out Half-Width/Height Does Work

You stated you tried half-width/height calculations in your attempt to center the image on the circumference of a circle at some angular reference (as I understand your question). It seems that should and does work. Check out this...

Example Fiddle

The circle and image colors are for visual reference, but the image positioning is done by:

LESS

//define circle position
@r: 100px;
@x: 175px;
@y: 150px;
.setImage(@w, @h, @a) {
    //@a is angle from HORIZONTAL but moves clockwise 
    //(based on radians unless units are given)
    width: @w;
    height: @h;
    left: (@x + ( @r *  cos(@a) ) - (@w / 2));
    top: (@y + ( @r *  sin(@a) ) - (@h / 2));
}
.test1 {
  .setImage(40px, 40px, -35deg);
}
.test2 {
  .setImage(60px, 30px, -80deg);
}
.test3 {
  .setImage(90px, 20px, -150deg);
}
.test4 {
  .setImage(40px, 70px, -240deg);
}
.test5 {
  .setImage(20px, 90px, -295deg);
}

CSS Output

.test1 {
  width: 40px;
  height: 40px;
  left: 236.9152044288992px;
  top: 72.64235636489539px;
}
.test2 {
  width: 60px;
  height: 30px;
  left: 162.36481776669305px;
  top: 36.5192246987792px;
}
.test3 {
  width: 90px;
  height: 20px;
  left: 43.39745962155612px;
  top: 90px;
}
.test4 {
  width: 40px;
  height: 70px;
  left: 104.99999999999996px;
  top: 201.60254037844385px;
}
.test5 {
  width: 20px;
  height: 90px;
  left: 207.26182617406997px;
  top: 195.630778703665px;
}

Works Even With Rotated Images

Assuming you set your images to have transform-origin: center center then it works to keep them on center even if the images are rotated at some angle.

See Rotated Image Example Fiddle

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