簡體   English   中英

以絕對位置居中圖像(上,左)

[英]Centering an image with absolute position (top, left)

我正在使用參數方程式將圖像定位在圓周圍( 如何計算圓的圓周上的點?

我使用簡單的數學運算就更少了:

// 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) );
}

我遇到的麻煩是,這會將圖像定位在圖像的左上角而不是圖像的中心,因此無法解決其具有的高度和寬度的視覺偏移。 嘗試按高度/ 2進行調整,寬度/ 2不起作用,因為每個圖像的角度都不同。

有沒有一種簡單的方法可以以這種方式定位圖像,使其以x,y為中心?

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

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

不用計算就可以做到:

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

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

現場演示

減去一半的寬度/高度確實有效

您說過嘗試將寬度/高度的一半計算出來, 以使圖像在某個角度參考的圓圓周上居中 (據我所知,這是您的問題)。 似乎應該而且確實可行。 看看這個...

小提琴的例子

圓圈和圖像的顏色僅供參考,但是圖像的定位方法是:

//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輸出

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

即使旋轉圖像也可以使用

假設您將圖像設置為具有transform-origin: center center那么即使圖像旋轉了某個角度,它也可以使它們居中。

請參見旋轉圖像示例小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM