Responsive font size with CKEditor

CKEditor is very nice WYSIWYG editor for web apps. It saves you many days of coding in exchange for just hours spent in DOM inspector trying to come up with CSS rules for it to play nice with your existing layout. But occasionally you will still need to write some code to work around their design choices. One of these cases is when you want to use responsive font size. So, how do you do that? First, you need to give CKEditor the list of font sizes:

CKEDITOR.inline(editable, {
    fontSize_sizes: '1/1vh;2/2vh;3/3vh;4/4vh;5/5vh;6/6vh;'
});

This is straightforward and documented. The problem that comes with it, however, is that font sizes in preview are too small. You are welcome to try and figure out why but, if you don’t feel like wasting your time, here is a hack that can help:

// buildPreview() is called every time "size" dropdowm is opened
CKEDITOR.style.prototype.buildPreviewOriginal = CKEDITOR.style.prototype.buildPreview;
CKEDITOR.style.prototype.buildPreview = function (label) {
    var result = this.buildPreviewOriginal (label);
    var match = /^(.*)font-size:(\d+)vh(.*)$/.exec (result);
    if (match) {
        // apparently ckeditor uses iframe or something that breaks vh units
        // we shall use current window height to convert vh to px here
        var pixels = Math.round (0.01 * window.innerHeight * parseInt (match[2]));
        result = match[1] + 'font-size:' + pixels + 'px' + match[3];
    }
    return result;
};

This looks much better now doesn’t it?

Ask a Question

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Old stuff

November 2014
M T W T F S S
« Aug   Jan »
 12
3456789
10111213141516
17181920212223
24252627282930

Oh, btw…


%d bloggers like this: