Damian Pereira
Damian Pereira

Reputation: 513

Make a div adapt to rotated children size with CSS

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.

Upvotes: 1

Views: 239

Answers (2)

vector001
vector001

Reputation: 33

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.

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272827

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>

Upvotes: 2

Related Questions