kthornbloom
kthornbloom

Reputation: 3720

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:

Upvotes: 10

Views: 11585

Answers (3)

squarecandy
squarecandy

Reputation: 5107

Based on @Turnip's answer, here's what I ended up using this:

/* Maintain Height While Loading Trick */
figure {
  background: #999;
  width: 100%;
  overflow: hidden;
  line-height: 1;
}
figure:before {
  content: "";
  display: block;
  padding-top: 100%;
  float: left;
}

/* some other CSS that's probably in your project already */
div {
  max-width: 25%;
  margin: 10px;
}
img {
  max-width: 100%;
  height: auto;
  vertical-align: top;
}
<div>
  <figure>
    <img src="https://picsum.photos/4000/4000" alt="">
  </figure>
</div>

<h1>Some stuff below the image. Is it jumpy?</h1>

Upvotes: 2

Turnip
Turnip

Reputation: 36632

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>

Upvotes: 18

Josh Crozier
Josh Crozier

Reputation: 240858

One option would be to use viewport percentage units. In this case, 50vw is 50% of the viewport. If the div is a root element and its width is relative to the viewport, then this work work as expected. You would otherwise have to calculate the height relative to the viewport for this to work.

For example:

div {
  width: 50vw;
  min-height: 50vw;
  background: #000;
}
<div></div>

Upvotes: 6

Related Questions