You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CSS calc响应式容器内放置占满容器宽度的自适应图片

解决方法

你需要对现有CSS做以下几处调整:

  • 重置<figure>元素的默认外边距,同时让<figure>、<picture>两个中间容器完全撑满外层的3:2响应式盒子
  • 给图片新增高度限制,让图片的宽高都以父容器尺寸为基准适配

修改后的完整CSS代码如下:

:root{
--varWidth: 80vw;
--varHeight: calc(80vh + 3.5vh);
}

.aspectRatio3x2 {
    --varAspectRatio: calc( 3 / 2);
    --varCalcHeight: min(calc(var(--varWidth) / var(--varAspectRatio)), var(--varHeight));
    height: var(--varCalcHeight);
    width: calc(var(--varCalcHeight) * var(--varAspectRatio));
    background-color: gold;
    overflow: hidden; /* 新增:避免内容溢出容器 */
}

/* 新增:中间容器撑满父级 */
.aspectRatio3x2 figure,
.aspectRatio3x2 picture {
    width: 100%;
    height: 100%;
    margin: 0; /* 清除figure默认外边距 */
}

.imgMain, .imgOther {
    object-fit: contain;
    width:100%;
    height: 100%; /* 新增:高度继承父容器 */
    max-width:100%;
    border: 2px solid hsla(0, 0%, 100%, .15);
}

.imgMain{
    border-bottom: none;
}

/* Other CSS */
.contentContainer {
    width: 100%;
    height: auto;
    padding: min(4vh, 3.5vw);
    background: hsl(0 0% 10%);
    background:red;
}

.pageDefault {
    width:100%;
    background-color: black;
}

.pageDefault article {
    position: relative;
    margin: 0 auto;
    background: lime;
}

如果需要图片完全铺满容器不留空白(允许裁剪图片边缘),把.imgMain的object-fit属性值改为cover即可。

内容的提问来源于stack exchange,提问作者CES

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 05:42:02