How to Set Text of TinyMCE Editor to Center Align?

I’m trying to make it so a text editor that uses TinyMCE will have the text center-aligned by default. I’ve tried executing a command, and I’ve also tried linking to a custom CSS, but neither option worked. I’m not sure if my setup functions are written wrong, if my custom css isn’t reaching to the right file location, or if the custom css isn’t connecting to the right element.

Here is the TinyMCE init code:

<script type="text/javascript">
    
tinymce.init({
    selector: '#writeTitle',
    width : "1000",
    height: '80',
    //skin: 'oxide-dark',
    //content_css: 'https://headcanon.ca/wp-content/uploads/custom-css-js/70.css',
    menubar: false,
    statusbar: false,
    toolbar: false,
    setup: function (editor) {
        editor.on('init', function (e) {
           editor.execCommand('JustifyCenter', false);
           editor.execCommand('FontSize', '32px', false);
        });
        editor.on('init keydown change', function (e) {
           document.getElementById('data').innerText = editor.getContent();
        });
    },
    
    //
});
</script>

And here is the CSS I’ve been trying:

.mce-content-body {
    background-color: #444445!important;
    color:#FFF!important;
    text-align:center;
}

Answer

Once you have the CSS you want to use for this purpose you can use either the content_css or content_style configuration options in TinyMCE to pass the appropriate CSS to TinyMCE.

Here is an example: https://fiddle.tiny.cloud/36haab

This uses the following CSS:

    html, body {
        height: 100%;
    }

    html {
        display: table;
        margin: auto;
    }

    body {
        display: table-cell;
        vertical-align: middle;
    }

I am not suggesting this is the only CSS that will do what you want but in my testing it does center all the text in the editor.

Leave a Reply

Your email address will not be published. Required fields are marked *