skip to Main Content

Let’s say we have responsive rectangle. I need to fit square element into rectangle and it should be 100% of its height. How could you do it with CSS only (no SVG and JS, no fixed sizes)? In other words: make child element’s width equal to parent element’s height?

It’s easily done with SVG as child element using viewbox property but I need pure CSS solution.

<div style="width: 95vw; height: 100%; border: 2px solid #f00">
  <div style="border: 2px solid #0f0">I'm 100% of parent's height but also I'm not square</div>
</div>

3

Answers


  1. you could use the padding-top propertie

    <div class="rectangle">
      <div class="square"></div>
    </div>
    
    
    .square {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%; 
      height: 100%; 
      background-color: red;
    }
    
    .rectangle {
      position: relative;
      width: 0;
      height: 100%;
      padding-top: 100%; 
    }
    
    
    
    
    Login or Signup to reply.
  2. You can use the aspect-ratio property to ensure that the inner element is always 1:1, or square. You will have to define some height on your parent element though.

    * {
      box-sizing: border-box;
    }
    
    .parent {
      width: 95vw;
      height: 100px;
      border: 2px solid #f00;
    }
    
    .child {
      aspect-ratio: 1/1;
      height: 100%;
      border: 2px solid #0f0;
    }
    <div class="parent">
      <div class="child">I'm 100% of parent's height and square</div>
    </div>
    Login or Signup to reply.
  3. Modern browsers have an aspect-ratio property.

    If you give the child 100% of the parents height then it’s width will be the same.

    Note that in your snippet there was no real height to the parent so I’ve, arbitrarily, give it a height just for demo. In a real situation I expect the parents setting of 100% would have something to set itself to.

    <div style="width: 95vw; height: 300px; border: 2px solid #f00">
      <div style="border: 2px solid #0f0; aspect-ratio: 1 / 1; height: 100%;">I'm 100% of parent's height but also I'm not square</div>
       Get </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search