如何让@monaco-editor/react编辑器大小自适应其父div容器
问题原因
布局错乱是两个原因共同导致的:
- Flex布局的子项
.item仅设置了flex-grow:1,默认flex-basis为auto,子项宽度会优先跟随内容宽度计算,而非均分父容器宽度,monaco编辑器的默认宽度会直接撑大父容器。 - 未给
@monaco-editor/react的Editor组件指定适配父容器的尺寸,编辑器会使用内置默认宽高渲染,突破父容器限制。
解决方法
- 调整Flex子项样式,确保两个
.item均分容器宽度,且限制内容不会溢出,修改后的CSS如下:
html, body { height: 100%; margin: 0px; } .container { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: #999; padding: 10px; margin: 0px; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: space-evenly; align-items: stretch; } .item { background-color: #efefef; flex: 1 1 0; /* 等效于flex-grow:1; flex-shrink:1; flex-basis:0; 保证两个子项均分宽度 */ position: relative; overflow: hidden; } .item + .item { margin-left: 10px; }
- 给Editor组件显式指定宽高为100%,适配父容器尺寸,修改后的JSX如下:
<div className="container"> <div className="item"> <Editor width="100%" height="100%" onMount={this.editorDidMount} ></Editor> </div> <div className="item"> <Editor width="100%" height="100%" onMount={this.editorDidMount} ></Editor> </div> </div>
如果仍有高度适配问题,给.item额外添加height: 100%属性即可。
内容的提问来源于stack exchange,提问作者sak
相关产品推荐
相关产品推荐

