我有一个流体宽度div,它在另一个块级元素中。
HTML
<div></div>
CSS
div {
width:50%;
min-height: /*equal to width */;
}
我希望min-height设置等于宽度,这样它就是方形,除非内容太多。此时,它应该垂直扩展。这可以用CSS实现吗?
我尝试过的事情:
答案 0 :(得分:7)
因为填充是相对于元素宽度的,所以可以使用伪元素通过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>
答案 1 :(得分:1)
一种选择是使用viewport percentage units。在这种情况下,50vw
是视口的50%。如果div
是根元素且其width
相对于视口,则此工作按预期工作。否则,您必须计算相对于视口的高度才能使其工作。
例如:
div {
width: 50vw;
min-height: 50vw;
background: #000;
}
<div></div>
答案 2 :(得分:0)
根据@ Turnip的回答,这里我最终使用了这个:
/* 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;
}
&#13;
<div>
<figure>
<img src="https://picsum.photos/4000/4000" alt="">
</figure>
</div>
<h1>Some stuff below the image. Is it jumpy?</h1>
&#13;