Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CKEditor remove inline img style

Tags:

ckeditor

I am using a responsive image technique setting a max-width of 100% with CSS.

This isn't working for any images added through CKEditor, as an inline style is added.

In CSS I have added a style to override the width, which works, but height: auto doesn't, so the images is stretched.

I need to find a way to stop CKEditor from adding the inline style in the first place.

I am using CKEditor 4.x

Thank you

like image 215
ccdavies Avatar asked Nov 29 '22 02:11

ccdavies


2 Answers

A far better alternative to the accepted answer is to use disallowedContent (see docs), as opposed to allowedContent.

Using allowedContent requires you to create a rather large white-list for every possible tag or attribute; where as disallowedContent does not; allowing you to target the styles to ignore.

This can be done like so:

CKEDITOR.replace( 'editor1', {
    disallowedContent: 'img{width,height};'
});
like image 129
Joseph Woodward Avatar answered Dec 21 '22 18:12

Joseph Woodward


Since version 4.1, CKEditor offers so called Content Transformations and already defines some of them. If you restrict in your config.allowedContent that you don't want to have width and height in <img> styles, then editor will automatically convert styles to attributes. For example:

CKEDITOR.replace( 'editor1', {
    allowedContent: 
        'img[!src,alt,width,height]{float};' + // Note no {width,height}
        'h1 h2 div'
} );

then:

<p><img alt="Saturn V carrying Apollo 11" class="left" src="assets/sample.jpg" style="height:250px; width:200px" /></p>

becomes in the output:

<p><img alt="Saturn V carrying Apollo 11" height="250" src="assets/sample.jpg" width="200" /></p>

and, as I guess, it completely solves your problem.

like image 22
oleq Avatar answered Dec 21 '22 16:12

oleq