在容器内居中旋转 div

Centering rotated div inside container

我正在尝试制作一个 90deg 价格标签,但是我不确定为什么它没有按照我想要的方式进行,我希望标签与顶部和右侧(顶部:0 和 right:0).

它不是那样做的, 代码

<div class='box'>
  <div class='price-tag'>
    .12
  </div>
</div>
.box{
  margin:10em;
  height:100px;
  width:100px;
  position:relative;
  background:red;
}

.box .price-tag{
  background:yellow;
  position:absolute;
  top:0;
  right:0;
  display:inline-block;
  transform:rotate(90deg) translate(50%, 0%);
}

JSFiddle

将任何元素旋转 90 度时,您要查找的是:

transform: rotate(90deg) translate(calc(50% - (height/ 2)), calc(50% - (width/ 2)))

或更具体的情况:

transform: rotate(90deg) translate(calc(50% - (18px / 2)), calc(50% - (44px / 2)))

这是因为当您旋转它时,您会希望 translate 在水平轴和垂直轴上都偏移 50%,以便将它放回到原来的位置。但是,这只会将 corner 定位到先前位置所在的位置。

要更正此问题,您还需要从新的水平偏移中减去 heighthalf,以及 half 来自新垂直偏移的 width,利用 calc() 函数。

这可以在以下工作中看到:

.box {
  /*margin: 10em;*/ /* -- Removed for demo fiddle */
  height: 100px;
  width: 100px;
  position: relative;
  background: red;
}

.box .price-tag {
  background: yellow;
  position: absolute;
  top: 0;
  right: 0;
  display: inline-block;
  transform: rotate(90deg) translate(calc(50% - (18px / 2)), calc(50% - (44px / 2)))
}
<div class='box'>
  <div class='price-tag'>
    .12
  </div>
</div>

问题是你的transform-origin,你需要设置成top right

.box {
  margin: 10em;
  height: 100px;
  width: 100px;
  position: relative;
  background: red;
}

.box .price-tag {
  background: yellow;
  position: absolute;
  top: 0;
  right: 0;
  display: inline-block;
  transform-origin: top right;
  transform: rotate(90deg) translateX(100%);
}
<div class='box'>
  <div class='price-tag'>
    .12
  </div>
</div>

另一种方法是通过调整 writing-mode

来改变文字方向

.box {
  height: 100px;
  width: 100px;
  position: relative;
  background: red;
}

.box .price-tag {
  background: yellow;
  position: absolute;
  top: 0;
  right: 0;
  writing-mode: vertical-rl; /* tb-rl if you want old browser support*/
}
<div class='box'>
  <div class='price-tag'>
    .12
  </div>
</div>