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

如何仅用CSS实现绝对定位区块与3/2比例响应式图片的底部对齐

纯CSS实现方案

核心原理是利用aspect-ratio固定图片3/2的响应式比例,再通过偏移量直接对齐,完全不需要JS计算:

核心修改点

  • 给img启用aspect-ratio: 3/2,删掉多余的padding-bottom属性,图片高度会自动按照宽3高2的比例响应式变化
  • 把section的定位从bottom:0改为top: calc(100% - 4vw),因为你的section总高度是8vw,4vw刚好是一半高度,偏移后section1的底部就会和图片底部完全对齐,section3会自动覆盖图片底部4vw高度的区域

修改后完整代码

main{
    height:100%;
    width: 100%;
    padding: 3.5vh; 
}
div{
    position: relative;
    max-width: 800px;
    margin: 0 auto;
}
img{
    object-fit: contain;
    aspect-ratio: 3/2;
    width: 100%;
}
div section{
    position: absolute;
    display: grid;
    grid-template-columns: 30% 70%;
    grid-template-rows: 50% 50%;
    grid-template-areas:
        "section1 section3"
        "section2 section3";
    top: calc(100% - 4vw);
    height:8vw;
    width:100%;
}
.section1, .section2, .section3{
    width:100%;
    height:100%;
    font-size: 20px;
    font-weight:bold;
    color:black;
}
.section1{
    grid-area: section1;
    background-color: red;
}
.section2{
    grid-area: section2;
    background-color: blue;
}
.section3{
    grid-area: section3;
    background-color: green;
    opacity: .5;
}
<main>
    <div>
        <img src="../../images/portfolio/mainbnw.jpg" />
        <section>
            <div class="section1">
                section 1
            </div>
            <div class="section2">
                section 2
            </div>
            <div class="section3">
                section 3
            </div>
        </section>
    </div>
</main>

低版本浏览器兼容方案

如果需要兼容Safari 15.4以下不支持aspect-ratio的版本,可以用传统比例容器实现:

  1. 给img外层新增一个比例容器,样式设置为position: relative; width: 100%; padding-top: 66.666%;(2/3的百分比对应3/2的宽高比)
  2. 给img设置position: absolute; top: 0; left: 0; width: 100%; height: 100%;即可,其余代码和上面一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:57:03