居中旋转的div在容器内部

3
我正在尝试制作一个90deg的价格标签,但我不确定为什么它不能做到我想要的效果,我希望该标签能和顶部和右侧对齐(top:0和right:0)。
但它并没有做到这一点, 代码
<div class='box'>
  <div class='price-tag'>
    $23.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


这可能是您的变换的“原点” - 所以它旋转的方式与您预期的略有不同?如果您修改原点,然后微调变换,它是否符合您的要求:https://jsfiddle.net/hbegvko5/ ? - Jack
3个回答

2

另一种方法是通过调整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'>
    $23.12
  </div>
</div>


1
当将任何元素旋转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)))
这是因为当您旋转它时,您希望在水平和垂直轴上的偏移量都要减去50%,以便将其定位回先前的位置。但是,这只定位了先前位置的角落。
为了纠正这个问题,您还需要从新的水平偏移中减去的一半,从新的垂直偏移中减去的一半,并利用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'>
    $23.12
  </div>
</div>


1
问题在于你的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'>
    $23.12
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接