Issue #922Opened March 2, 2018by mbleverage0 reactions

QUESTION: Adding default styling to a component

Question

I have been working on integrating grapesjs into a new development I'm working on. I have had much success with the documentation and wiki forum but am running into a few issues I'm hoping someone out there can help me with. I am working with a mobile view only, I have set the default device to mobile and hidden the option to change.

When I insert an image, I would like the default css to include max-width: 100% as if I load a large image into the mobile view I will get an image much larger than the screen I'm looking at.

I have tried:

blockManager.get('image').set({
    style:{
        'max-width':'100%'
    }
});

But I realize that might be an incorrect use and maybe only width (not max-width) is valid there. I have also tried using the cssComposer with no success.

var sm = editor.SelectorManager;
var cssComposer = editor.CssComposer;
var sel1 = sm.add('img');
var rule = cssComposer.add([sel1]);
rule.set('style', {'max-width': '100%'});

Any help would be greatly appreciated. Thank you.

Answers (3)

artfMarch 4, 20180 reactions

Your change on the block doesn't work because you don't change the actual component (just the block's property)

editor.BlockManager.get('image').get('content').style = { 'max-width':'100%' }

With cssComposer instead, by default, selectorManager accepts classes

...
var sel1 = sm.add('img'); // here you'r adding `.img` selector and not `img`

An easier way to add custom CSS might be this one

editor.addComponents('<style> ... </style>');

But be careful, if store your templates and then run this command on any refresh this will continue to create styles. For default CSS I'd recommend:

grapesjs.init({
  // CSS that could only be seen (for instance, inside the code viewer)
  protectedCss: 'img { ... }',
  
  // If have an external file, like for example, some reset CSS
  // you can use this
  canvas: {
	styles: ['https://...file.css']
  }
})
mbleverageMarch 5, 20180 reactions

Thank you! I was able to get that working with: protectedCss: 'img {max-width:100%;}', I have the same issue with videos and iframes (for youtube) being dropped onto the template larger than the screen size and the protectedCss solution did not work for those. Any suggestions?

artfMarch 6, 20180 reactions

protectedCss is loaded so the CSS is here, if it doesn't work probably your CSS technique is not correct

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.