How to get the ace editor to adjust to its parent div

╄→гoц情女王★ 提交于 2019-11-30 17:25:16
scain

You can achieve what you want in two manners. I have created a jsfiddle showing the css and javascript used to resize the ace-editor to its container.

The css used is to make it so the editor takes up the width and height of the container, so that editor.resize() can properly calculate the size the editor should be.

I recommend the following to get the editor.resize() to work.

<style type="text/css" media="screen">
    #editor {
        width: 100%;
        height: 100%;
    }
</style>

However if you want to maintain using the current css you have for #editor the following will work.

<style type="text/css" media="screen">
    #editor {
        position: absolute; /* Added */
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
   }
</style>

and add position: relative; to the container, so that the absolutely positioned editor is correctly positioned inside its container. As to how this works I refer you to Absolute positioning inside relative positioning.

You can achieve by the following way. Run the code snippet for example.

var editor = ace.edit("editor");
        editor.setTheme("ace/theme/tomorrow_night");
        editor.session.setMode("ace/mode/xml");
        editor.session.setUseSoftTabs(true);
#parent {
    width:50%;
    height: 600px;
    display:inline-block;
    position:relative;
}
#editor {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.3.3/ace.js"></script>
<html>
   <body>
      <div id="parent">
          <div id="editor"></div>
      </div>
   </body>
</html>

Using jquery-ace I've managed this simply by using:

    $('#php_code').ace({
        theme: 'chrome',
        lang: 'php',
        width: '100%',
        height: '300px'
    })

I got it working with simple CSS:

#container{
    height:80vh;
}

#editor {
    width: 100%;
    height: 100%;
    position: relative;
}

The key property is position:relative, overriding the default position:absolute of the ace editor, which produces the parent container being unable to adjust its content.

<div id="container">
    <pre id="editor">
        &#x3C;div&#x3E;
        &#x9;&#x9;this is a div
        &#x9;&#x3C;/div&#x3E;
    </pre>
</div>

<script>
    $(document).ready(function() {
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/TextMate");
        editor.session.setMode("ace/mode/html");
    });
</script>

Reset its settings back to the browser default, which by design fit the parent container.

#editor {
    width: inherit !important;
}

I'm using the react-ace wrapper for reactjs. It could be beneficial to any ace wrapper which have some defaults overwritten.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!