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:
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With