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

Electron环境下div高度不生效且无法顶置窗口的问题求助

问题:修改div高度无效且无法贴到窗口顶部

我尝试修改div的height属性,但高度没有变化,同时无法让该div贴到窗口顶部,以下是我的代码:

CSS

.shop {
   position: absolute;
   width: 200px;
   height: 100%;
   min-height:100%;
   left: 1022px; 
   font-family: "Times New Roman", Times, serif;
   border: 3px solid #73AD21;
   padding: 10px; 
   overflow-y:scroll;
   text-align: center;
   display:inline-block;
}

HTML

<div class="shop">
   <h1 style="text-align: unset;">Shop</h1>
   <div class="upgrades">
   </div>
   <div class="buildings">
     <button>
       <div class="clicker">
         <h1 class="title">Clicker</h1>
         <h2 id="cost">Cost: 15 Dollar's</h2>
         <p class="description">A nice little clicker kind of look's like a glove...</p>
       </div>
     </button>
     <button>
       <div class="snow">
         <h1 class="title">Snowglobe's</h1>
         <h2 id="cost">Cost: 350 Dollar's</h2>
         <p class="description">Shake it up to get some cash :]</p>
       </div>
     </button>
     <button>
       <div class="farm">
         <h1 class="title">Farm's</h1>
         <h2 id="cost">Cost: 500 Dollar's</h2>
         <p class="description">Farm some food and sell if this might be helpful in the long run....</p>
       </div>
     </button>
     <button>
       <div class="factory">
         <span class="tooltipfac">What is this? Well we got to find out by buying it :]</span>
         <h1 class="title">Factorie's</h1>
         <h2 id="cost">Cost: 5600 Dollar's</h2>
         <p class="description">Hey a factory might help to build stuff to help!</p>
       </div>
     </button>
   </div>
</div>

我已尝试上述代码,期望div能贴到窗口顶部,但未实现。效果对比:高亮区域为期望位置,绿色边框为当前div。
注:我使用Electron运行该窗口和代码。


修复方案

核心问题点

  1. 绝对定位元素未设置top: 0,默认停在文档流原有位置,无法顶到窗口顶部
  2. height: 100%需要父容器(html、body)先设置100%高度,否则百分比没有参照基准
  3. padding:10px会额外增加元素高度,导致超出窗口,且未用box-sizing:border-box控制盒模型
  4. display:inline-block对绝对定位元素无效,属于冗余属性

修复后的CSS代码

/* 先给根元素设置高度,清除默认边距 */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.shop {
  position: absolute;
  width: 200px;
  height: 100%;
  top: 0; /* 强制贴顶 */
  left: 1022px; 
  font-family: "Times New Roman", Times, serif;
  border: 3px solid #73AD21;
  padding: 10px; 
  overflow-y: scroll;
  text-align: center;
  box-sizing: border-box; /* 让padding和border包含在宽高内 */
}

额外优化建议

  • 多个元素使用了重复的id="cost",ID必须唯一,建议改为class="cost"
  • 英文所有格写法错误,比如Dollar's应改为Dollars(不需要加单引号)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:42:52