Transform skew child divs but also keep them inside parent container

96 Views Asked by At

I have a parent container width 3 (or more) child div's including images. When I skew my child divs they are bigger than the parent div so they are not nicely skewed.

I want to achieve this: goal

I have tried the following:

<div class="parent">
   <div class="child">
     <!-- Image -->
   </div>
   
   <div class="child">
     <!-- Image -->
   </div>

   <div class="child">
     <!-- Image -->
   </div>
</div>

With the following style:

.parent{
   display:flex;
   flex-wrap:wrap;
   justify-content: space-between;
}

.child{
    width:30%;
    height:375px;
    transform: skew(-45deg);
    overflow:hidden; //Because i want to insert images inside it
    transform-origin: bottom right;
    background:red;
}

But this give me not the right result

current result

So to clarify, this is what I want:

I want this

but this is what I get:

This is what I get

1

There are 1 best solutions below

2
A Haworth On

For a slant of 45degrees this can be achieved if we think of three red squares which are then skewed. They need to be 25% width of their parent-less-gap-allowance, not 30%, to leave enough room for the slanted part of the last child.

One way of doing this for any aspect ratio of the overall container is to separate that from the direct parent of the child elements.

This snippet has a container with the aspect ratio 1 / 1 (as given in the comments). The height has been set at 100vh just for this demo.

The parent of the children is inside it and width calculated to sit in three quarters of the overall container plus an allowance for the gap.

The gap is set as a CSS variable so it can be easily changed if required.

<style>
  * {
    box-sizing: border-box;
    margin: 0;
  }
  
  .container {
    width: 100vh;
    aspect-ratio: 1 / 1;
    display: flex;
    align-items: center;
    background: lightblue;
  }
  
  .parent {
    --gap: 10px;
    --halfgap: calc(var(--gap) / 2);
    width: calc(75% + var(--halfgap));
    display: flex;
    justify-content: space-between;
  }
  
  .child {
    width: calc(100% / 3);
    aspect-ratio: 1 / 1;
    background: red;
    border: solid 1px black;
    transform: skewX(-45deg);
    transform-origin: bottom left;
    box-sizing: border-box;
    margin: 0 var(--halfgap);
  }
  
  .child:first-child {
    margin: 0 var(--halfgap) 0 0;
  }
  
  .child:last-child {
    margin: 0 0 0 var(--halfgap);
  }
</style>
<div class="container">
  <div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
  </div>
</div>