VGO Exclusive
VGO Exclusive

Reputation: 183

Centering rotated div inside container

I'm trying to make a 90deg pricetag, however I'm unsure why it isn't doing what I want it to do, I want the tag to matchup with the top and right (top:0 and right:0).

It's not doing that, Code

<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

Upvotes: 3

Views: 84

Answers (3)

dippas
dippas

Reputation: 60543

The problem is your transform-origin, you need to set it to 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>

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 272608

Another way is to change the text direction by adjusting the 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>

Upvotes: 2

Obsidian Age
Obsidian Age

Reputation: 42304

When rotating any element by 90 degrees, what you're looking for is:

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

Or more specific to this case:

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

This is because when you rotate it, you'll want the translate to be off by 50% on both the horizontal and vertical axis in order to position it back where it previously was. However, this only positions the corner where the previous position was.

To correct this, you'll also want to subtract half of the height from the new horizontal offset, and half of the width from the new vertical offset, making use of the calc() function.

This can be seen working in the following:

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

Upvotes: 1

Related Questions