Search code examples
htmlcssheightwidth

Set min-height equal to width


I have a fluid width div which is within another block-level element.

HTML

<div></div>

CSS

div {
    width:50%;
    min-height: /*equal to width */;
}

I want the min-height set equal to the width so that it is a square shape unless there is too much content. At that point, it should expand vertically. Can this be achieved with CSS?

What I've tried:

  • Using percentage paddings or margins, but this only sets height, not max--height and pushes the content down.

Solution

  • Because padding is relative to an elements width, you can use a pseudo element to force a min height by using padding-top: 100%;:

    div {
      float: left;
      margin: 10px;
      width: 25%;
      background: lightGreen;
      position: relative;
    }
    
    div:before {
      content: "";
      display: block;
      padding-top: 100%;
      float: left;
    }
    <div></div>
    
    <div>
      div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content. div with content.
      div with content. div with content. div with content. div with content. div with content. div with content.
    </div>
    
    <div>
      div with content. div with content.
    </div>