placing background image in a rhombus shaped container is causing the container to lose its shape

You need to increase the width/height of the image and you may consider flexbox to easily center it. It then overflow equally from the 4 sides and it will cover the gap:

.box {
  margin: 50px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  border: 1px solid;
  border-radius: 20px;
  overflow: hidden;
  transform: rotate(45deg);
}

.box img {
  transform: rotate(-45deg);
  width: 141%;
  height: 141%;
  flex-shrink: 0;
}
<div class="box">
  <img src="https://picsum.photos/200/200?image=1069">
</div>

Why exactly 141%?

To be more precise and accurate it’s exactly sqrt(2) * 100% ~ 141%. Here is an illustration to better understand (I removed the border-radiusand applied only rotation to both box and image):

enter image description here

The green line is the width we want to caclulate (or the height since we have a square) and the red lines are the width/height of the box and Pythagore said that the formula is W² = h² + w² and h = w so we have W = sqrt(2) * h.

If you want to be more accurate we can also reduce the space created by border-radius. Considering how radius works we can draw this illustration:

enter image description here

The red lines define the value of border-radius (20px in this case). The green line is equal to sqrt(2)*20px [using the previous formula] and the distance we need to remove (defined by the orange line) is simply sqrt(2)*20px - 20px ~ 0.41 * 20px ~ 8.28px. So the final code could be:

.box {
  margin: 50px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 200px;
  border: 1px solid;
  border-radius: 20px;
  overflow: hidden;
  transform: rotate(45deg);
}

.box img {
  transform: rotate(-45deg);
  width: calc(141% - 8.28px);
  height: calc(141% - 8.28px);
  flex-shrink: 0;
}
<div class="box">
  <img src="https://picsum.photos/200/200?image=1069">
</div>

The above formula works only for this particular and easy case. The calculation may become more complex for other situation

Leave a Comment