Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 587
kthornbloom Avatar asked Dec 03 '15 21:12

kthornbloom


People also ask

Is width and height same?

Height: When a rectangle is drawn with horizontal and vertical sides, the word height makes it clear which dimension is meant; height labels how high (how tall) the rectangle is. That makes it easy to indicate the other dimension—how wide the rectangle is from side to side—by using the word width.

What is min height and Min width in CSS?

The min-height property defines the minimum height of an element. If the content is smaller than the minimum height, the minimum height will be applied. If the content is larger than the minimum height, the min-height property has no effect.


2 Answers

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>
like image 188
Turnip Avatar answered Nov 03 '22 10:11

Turnip


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>
like image 24
Josh Crozier Avatar answered Nov 03 '22 11:11

Josh Crozier