1

I have a rotated div contained inside a box, and want the outside div to contain the rotated children exactly. Here's an example:

<div class="container"> <div class="box"/> </div> 
.box { content: ''; background-color: red; width: 100px; height: 100px; transform: rotate(45deg) } .container{ margin: 3rem; display: inline-block; border: 5px solid black; // padding: 19px; } 

This looks like this:

enter image description here

Adding the padding (commented above), I can approximate the result I want, which is this:

enter image description here

The problem is that it is not exact, and it is hard-coded instead of automatic.

3
  • 1
    You'd need JS to do that ....and a bunch of math/ Commented Apr 28, 2022 at 14:52
  • 1
    always the same angle? Commented Apr 28, 2022 at 15:11
  • I wanted a solution that worked no matter the angle, and even for multiple divs. The real world use case is a triangle arrow made with 2 rotated divs, which is off-center and I wanted to correct the box. Commented Apr 28, 2022 at 16:11

2 Answers 2

2

For 45deg it's easy

.box { --size: 100px; /* the size to define width,height and margin*/ content: ''; background-color: red; width: var(--size); height: var(--size); transform: rotate(45deg); margin: calc(0.207*var(--size)); /* 0.2071 = sin(45deg) - 1/2 */ } .container { margin: 3rem; display: inline-block; border: 5px solid black; }
<div class="container"> <div class="box"></div> </div>

Sign up to request clarification or add additional context in comments.

1 Comment

So the only real way of making it work with any angle would be to calculate the sin in js and provide it to css, and make a bunch of math. Thanks for this! It might be too complex for the value the thing I'm doing provides, but I'll keep it in mind.
0

I found transform-origin CSS property. MDN Docs

Though it leaves much to be desired, it might be sufficient to hack out certain types of effects.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.