In TinyMCE, I may insert an image and center it. And the code generated is as follows:
<p><img height="684" src="/static/media/uploads/about.jpg" style="margin-left: auto; margin-right: auto; display: block;" width="938" /></p>
However, when I save the textarea, the display: block;
style is removed.
I also tried the followings, but all in vain:
Set <p>
:
<p style="text-align: center;"><img ... ></p>
The style of <p>
is removed when I save the content of the textarea.
In tinymce.init
, set:
verify_html: false
Set valid_children: "+body[style]"
in tiymce.init
and add the following in textarea:
<style>
p img {
display: block;
}
</style>
Set the following in tinymce.init:
valid_styles: {
"img": "display"
}
So, how do I center an image in TinyMCE anyway?
Edit CSS
If you are able to insert css to your page, you could simply set the images property to display: block
:
p img {
display: block;
}
Edit TinyMCE
If you are not able to excess the css files , you can maybe somehow edit the TinyMCE editor, so that you are able to use its build in text-align: center
button, which should do the same, as your code does?
You can set the toolbar of your TinyMCE like so:
$('#your_editor').tinymce({
plugins: 'link,code,preview,autolink',
height: 350,
width: 750,
toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link image | preview code"
});
Within toolbar:
you can choose which buttons you want to add. Using aligncenter
you can create a button, which you can use to align your image to the center.
I came up with a work-around solution:
Modify tinymce.init
:
(a) Add Formats: add the class center
and necessary styles
to every centered block element including img
.
formats: {
aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'center',
styles: {display: 'block', margin: '0px auto', textAlign: 'center'}},
}
(b) Add JavaScript to display centered elements correctly in the editing window: replace previously added margin: 0px auto;
with margin: 0px auto; display:block; text-align: center;
:
var value = $('textarea').val();
value = value.replace('margin: 0px auto;', 'margin: 0px auto; display:block; text-align: center;');
$('textarea').val(value);
And then add the following in our own CSS file to display centered element correctly in the HTML page:
.center {
display: block;
margin: 0 auto;
text-align: center;
}
The above solution took me hours to figure it out, all because TinyMCE wouldn't want to save the style display: block;
created by its own!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With