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

为何两个wgs类div无法横向排列?求CSS布局排查方案

两个地鼠容器无法横向排列的问题排查

我想要在HTML里实现两个类似“地鼠”的div横向排列,期望效果如下:
期望效果
但目前实现的效果是这样的:
当前效果

我试过把两个带wgs类的div放到带block类的容器里,还设置了display: inline-block,但不管加不加这个容器,页面效果都没变化。

我的HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="mole.css">
    <script type="text/javascript" src="mole.js"></script>
  </head>
  <body>
      <div class="wgs">
        <img src="mole-head.png" class="wgs__mole-head" alt="mole-head">
        <img src="mole-hill.png" class="wgs__dirt-pile" alt="mole-hill">
      </div>
      <div class="wgs">
        <img src="mole-head.png" class="wgs__mole-head" alt="mole-head">
        <img src="mole-hill.png" class="wgs__dirt-pile" alt="mole-hill">
      </div>
  </body>
</html>

我的CSS代码:

.wgs {
  display: inline-block;
  height: 482px;
  position: absolute ;
  width: 640px;
}
.wgs__mole-head {
  display;
  height: 356px;
  position: absolute;
  width: 376px;
  margin-left: 109px;
}
.wgs__dirt-pile {
  height: 220px;
  position: absolute;
  width: 640px;
  bottom: 0;
}

请问我哪里操作错了,没法实现期望的布局?


问题原因及修复方案

1. 核心错误:绝对定位破坏流式布局

你给.wgs设置了position: absolute,这个属性会让元素脱离正常文档流——元素不再占据页面空间,也不会和其他元素产生排版互动,哪怕加了display: inline-block也没用,两个绝对定位的.wgs会默认重叠在页面左上角,自然没法横向排列。

2. 次要错误:CSS语法错误

.wgs__mole-head里的display;是无效代码,缺少冒号和属性值,浏览器会直接忽略这一行。

修复后的CSS代码

.wgs {
  display: inline-block;
  height: 482px;
  width: 640px;
  /* 去掉绝对定位,让元素回到正常流式布局 */
  position: relative; /* 新增:让内部绝对定位的子元素以当前容器为基准 */
  margin-right: 20px; /* 可选:添加间距避免元素紧贴 */
}

.wgs__mole-head {
  /* 保留绝对定位,父元素已设为relative,子元素会相对容器定位 */
  position: absolute;
  height: 356px;
  width: 376px;
  margin-left: 109px;
}

.wgs__dirt-pile {
  height: 220px;
  position: absolute;
  width: 640px;
  bottom: 0;
}

修复说明

  • 删掉.wgs的position: absolute后,display: inline-block就能正常生效,让两个容器横向排列。
  • 给.wgs添加position: relative,确保内部的地鼠头和土堆能相对于容器定位,不会跑到页面其他位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:25:21