Electron.js无框窗口调整大小时视口缩1px致边框消失问题
问题原因
当你设置useContentSize: true时,Electron会将窗口的width和height直接作为网页内容区域的精确尺寸。你的.main元素设置了width: 100%; height: 100%,同时带有1px边框,虽然box-sizing: border-box让边框包含在元素尺寸内,但窗口调整大小时,网页视口与元素尺寸的计算会出现偏差:.main的边框会占用内容区域的空间,再加上overflow: hidden属性,底部和右侧的边框会被挤出视口范围,导致无法显示。
修复方案
以下是三种可行的修复方式,你可以根据需求选择:
方案一:用calc调整.main的尺寸
通过calc减去边框的总宽度,确保元素不会超出视口:
* { box-sizing: border-box; } .main { width: calc(100% - 2px); /* 左右边框各1px,总宽度减2px */ height: calc(100% - 2px); /* 上下边框各1px,总高度减2px */ background-color: white; border: 1px solid #333; overflow: hidden; margin: 0; /* 移除auto margin避免额外偏移 */ } html, body { width: 100%; height: 100%; margin: 0; padding: 0; } .titlebar { width: 100%; height: 40px; -webkit-app-region: drag; background-color: white; }
方案二:移除useContentSize并调整窗口初始尺寸
放弃useContentSize,改用Electron默认的窗口外尺寸计算(outer size),此时窗口宽高会包含网页内容+边框,所以需要把初始宽高各增加2px(边框总宽度):
const createWindow = () => { const win = new BrowserWindow({ width: 502, // 原500px + 2px边框 height: 402, // 原400px + 2px边框 frame: false, // 移除useContentSize配置 }) win.loadFile('index.html').then(); }
方案三:给body添加padding适配边框
通过给body设置与边框宽度一致的padding,让.main元素在padding区域内渲染,避免边框被挤出:
* { box-sizing: border-box; } .main { width: 100%; height: 100%; background-color: white; border: 1px solid #333; overflow: hidden; margin: 0; } html { width: 100%; height: 100%; } body { margin: 0; width: 100%; height: 100%; padding: 1px; /* 与边框宽度匹配 */ } .titlebar { width: 100%; height: 40px; -webkit-app-region: drag; background-color: white; }
内容的提问来源于stack exchange,提问作者T. Feix
相关产品推荐
相关产品推荐

