我有一个包含div内的方形图像,并希望包含div具有与图像相同的尺寸。图像的大小各不相同,因此未预先知道。特别要注意的是,图像是div内唯一的东西(好吧,不是严格意义上的,但其他元素是绝对定位的,因此基本上可以忽略)。保留一个包含div的图像大小
我目前拥有的代码如下:
div.container, image {
display: block;
/* ensure enough room for other content in sidebar */
max-height: calc((100vh - 12em)/2);
/* don't allow image to escape sidebar boundaries */
max-width: 256px;
/* forces image to be square as it's originally square */
width: auto;
height: auto;
}
div.container {
position: relative;
margin: 1em auto;
}
我已经看到了有关使用padding-bottom
一些帖子;虽然这确实使得包含的div为正方形,但它不一定与图像的大小相同,因为图像的高度可能会被迫远小于div的高度。
有没有干净的解决方案呢?
你试过jQuery吗? –
我宁愿不使用Javascript,除非在CSS中没有办法做到这一点。 –
我认为你不能使用display:inline-block或浮动它吗? – wizzardmr42