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

HTML/CSS网页开发挑战求助:图片无法嵌入指定div问题

问题解决:图片无法嵌入second-div并实现左右布局

核心问题分析

你的代码里图片没法被second-div容纳且两个区块无法并排,主要原因有三点:

  1. inline-block元素间的空白字符会占据宽度,加上first-div的540px,总宽度超过binding-div的1080px,导致second-div被挤到下一行
  2. second-div未设置尺寸约束,图片会以原始尺寸显示,无法被容器包裹
  3. 图片路径用了反斜杠\,网页路径需用正斜杠/,否则可能导致图片加载失败

修复后的完整代码

CSS 代码

body {
    background-color: black;
}

.container-div {
    background-color: rgb(133, 63, 208);
}

.binding-div {
    margin: 130px 205px;
    background-color: rgb(27, 134, 88);
    width: 1080px;
    height: 446px;
    /* 用flex布局替代inline-block,彻底解决空白字符问题 */
    display: flex;
}

.first-div {
    background-color: rgb(29, 26, 232);
    width: 540px;
    height: 446px;
    text-align: center;
}

.second-div {
    width: 540px;
    height: 446px;
    /* 约束图片显示范围 */
    overflow: hidden;
}

/* 让图片适配容器尺寸,保持比例不拉伸 */
.second-div img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

h1 {
    color: white;
    width: 60%;
    margin: 60px auto 20px auto;
}

p {
    color: white;
    width: 60%;
    margin: 0 auto;
}

.bottom-p {
    margin: 140px auto 40px auto;
}

HTML 代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Stat Card</title>
        <link rel="stylesheet" href="css/styles.css" />
    </head>
    <body>
        <div class="container-div">
            <div class="binding-div">
                <div class="first-div">
                    <h1>Get insights that help your business grow.</h1>
                    <p>
                        Discover the benefits of data analytics and make better decisions regarding
                        revenue, customer experience, and overall efficiency.
                    </p>
                    <p class="bottom-p">Challenge by Frontend Mentor. Coded by (insert name)</p>
                </div>

                <div class="second-div">
                    <!-- 修正路径斜杠为正斜杠 -->
                    <img src="Images/image-header-desktop.jpg" />
                </div>
            </div>
        </div>
    </body>
</html>

关键修改说明

  1. 将binding-div改为display: flex,自动让两个子区块并排,避免inline-block的空白字符问题
  2. 给second-div设置和first-div一致的宽高,并用overflow: hidden限制图片范围
  3. 给图片添加object-fit: cover,保证图片填满容器的同时不会拉伸变形
  4. 修正图片路径的斜杠方向,确保图片能正常加载

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:45:48