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

在CSS Grid列中匹配图片与标题高度(禁用Flex布局)

Grid布局实现桌面端图片高度匹配标题(无需Flex)

利用Grid布局行高由内容自动决定的特性,可实现桌面端图片高度与标题容器一致,移动端保留图片完整高度的效果。先修正原代码的两处关键错误:

  1. CSS中.wp-hero-image的grid-area拼写错误:hero-mage → hero-image,需与grid-template-areas定义的区域名一致
  2. HTML中图片的class名错误:wp-hero-mage → wp-hero-image,需与CSS选择器匹配

完整代码示例

CSS

.hero-title-image {
    display: grid;
    grid-template-areas: 'hero-title hero-image';
    /* 标题列自适应内容宽度,图片列占剩余空间 */
    grid-template-columns: auto 1fr;
}

.hero-title-container {
    grid-area: hero-title;
    font-size: 50px;
    /* 可选:添加内边距优化标题排版 */
    padding: 1rem;
}

.wp-hero-image {
    grid-area: hero-image;
    width: 100%;
    height: 100%; /* 强制图片高度与网格行高(标题容器高度)一致 */
    object-fit: cover; /* 裁剪图片适配容器,保持比例不拉伸 */
    object-position: center; /* 可选:设置图片裁剪的对齐中心 */
}

@media only screen and (max-width: 960px) {  
    .hero-title-image {
        grid-template-areas:
            'hero-title' 
            'hero-image';
        grid-template-columns: 1fr;
        grid-row-gap: 30px;
    }
    
    .hero-title-container {
        text-align: center;
        padding: 0;
    }

    .wp-hero-image {
        height: auto; /* 移动端恢复图片原始完整高度 */
    }
}

HTML

<div class="hero-title-image">
    <div class="hero-title-container">We help business owners in growth mode break through to the next level.</div>
    <img src="https://i.ibb.co/2359H9t/woman.jpg" class="wp-hero-image" />
</div>

核心逻辑说明

  • grid-template-columns: auto 1fr:确保标题列根据内容自适应宽度,图片列占据剩余空间,避免标题被挤压
  • 图片设置height: 100%:强制继承网格行的高度(由标题容器的高度决定)
  • object-fit: cover:保证图片比例不变,自动裁剪超出容器的部分,不会出现拉伸变形
  • 移动端重置图片height为auto,恢复图片完整高度展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:20:47