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

Frontend Mentor挑战:如何居中卡片并调整图片与div的尺寸

核心问题梳理

  1. 卡片无法居中:原有代码未给body设置占满视口高度的属性,也没有配置全局居中规则,卡片无法相对于页面居中
  2. 图片尺寸异常:首先CSS里写的.image类名和HTML中实际的图片容器类名image2不匹配,规则没有生效;其次没有给卡片、图片容器、img标签设置尺寸限制规则,也没有处理图片的适配逻辑

完整修改后的CSS代码

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

:root {
    /* Primary */
    --veryDarkBlue: hsl(233, 47%, 7%); /* 页面背景色 */
    --darkDesaturatedBlue: hsl(244, 38%, 16%); /* 卡片背景色 */
    --softViolet: hsl(277, 64%, 61%); /* 强调色 */

    /* Neutral */
    --White: hsl(0, 0%, 100%); /* 主标题、统计数字颜色 */
    --SlightlyWhite: hsla(0, 0%, 100%, 0.75); /* 正文颜色 */
    --SlightyWhite2: hsla(0, 0%, 100%, 0.6); /* 统计项标题颜色 */
}

* {
    font-family: 'Inter', sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    background-color: var(--veryDarkBlue);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2rem 1rem;
}

.card {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 100%;
    max-width: 540px;
    border-radius: 0.5em;
    overflow: hidden;
}

.info {
    background-color: var(--darkDesaturatedBlue);
    text-align: center;
    padding: 2.5rem 2rem;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

/* 类名和HTML保持一致,处理图片适配和紫色滤镜 */
.image2 {
    background-color: var(--softViolet);
    line-height: 0;
}
.image2 img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    mix-blend-mode: multiply;
    opacity: 0.8;
}

h1, h2 {
    color: var(--White);
}

p {
    color: var(--SlightlyWhite);
    line-height: 1.6;
}

.stat-head {
    color: var(--SlightyWhite2);
    letter-spacing: .1em;
    font-size: 0.8rem;
}

span {
    color: var(--softViolet);
}

.stats {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
    margin-top: 1rem;
}

@media (min-width: 1440px) {
    .card {
        flex-direction: row-reverse;
        max-width: 1110px;
    }

    .info, .image2 {
        width: 50%;
    }

    .info {
        border-top-left-radius: .5em;
        border-bottom-left-radius: .5em;
        text-align: left;
        padding: 4.5rem 5rem 4rem 4rem;
        justify-content: space-between;
    }

    .image2 {
        border-top-right-radius: .5em;
        border-bottom-right-radius: .5em;        
    }

    .stats {
        flex-direction: row;
        justify-content: space-between;
        width: 90%;
        margin-top: 2rem;
    }
}

关键修改说明

  • 给body添加min-height: 100vh和flex居中规则,实现卡片相对于页面垂直水平居中
  • 统一图片容器的类名,添加宽度100%、object-fit适配规则,搭配混合模式实现设计稿要求的紫色滤镜效果
  • 给卡片设置最大宽度限制,桌面端图片和内容各占50%宽度,匹配设计稿尺寸比例
  • 给内容区域添加padding和间距规则,调整文字样式更贴合设计稿要求
  • 给card添加overflow: hidden,自动裁剪子元素超出圆角的部分,不需要单独给子元素加圆角

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:18:02