Skip to content

Instantly share code, notes, and snippets.

@pacotole
Last active August 16, 2022 14:32
Show Gist options
  • Save pacotole/ee1ed6d2fa8a33376390 to your computer and use it in GitHub Desktop.
Save pacotole/ee1ed6d2fa8a33376390 to your computer and use it in GitHub Desktop.
Copy CSS rules to inline styles

Copy CSS rules to inline styles

It's very useful for email layout. You can add css styles in header <style> tag and after apply this script to get the HTML with inline styles.

// remove duplicates from array
// http://www.etnassoft.com/2011/06/24/array-unique-eliminar-valores-duplicados-de-un-array-en-javascript/
Array.prototype.unique = function(a){
  return function(){return this.filter(a)}
}(function(a,b,c){return c.indexOf(a,b+1)<0});

// get CSS rules from style tag
var cssrules = document.styleSheets[0].cssRules;

for (var i=0; i<cssrules.length; i++){
	var rule = cssrules[i];
	
	var items = document.querySelectorAll(rule.selectorText);
	
	for (var j=0; j<items.length; j++){
		// add to previous styles
		var style = items[j].getAttribute('style') || '';
		style = style + ';' + rule.style.cssText;
		// clean and remove duplicate styles
		style = style.replace(/\s*(:|;|,|\(|\))\s*/g, '$1');
		style = style.replace(/\s+/g, ' ');
		style = style.split(';').unique().join(';');
		// apply to tag
		items[j].setAttribute('style',  style);
		
		// console.log('style applied', items[j]);
	}
}

Copiar reglas CSS a estilos en linea

Es muy útil para maquetar correos. Creas los estilos en la etiqueta <style> y después aplicando este script puedes obtener fácilmente el HTML con los estilos en línea.

// util, remove duplicates from array
// http://www.etnassoft.com/2011/06/24/array-unique-eliminar-valores-duplicados-de-un-array-en-javascript/
Array.prototype.unique = function(a){
  return function(){return this.filter(a)}
}(function(a,b,c){return c.indexOf(a,b+1)<0});

// get CSS rules from style tag
var cssrules = document.styleSheets[0].cssRules;

for (var i=0; i<cssrules.length; i++){
	var rule = cssrules[i];
	
	var items = document.querySelectorAll(rule.selectorText);
	
	for (var j=0; j<items.length; j++){
		// add to previous styles
		var style = items[j].getAttribute('style') || '';
		style = style + ';' + rule.style.cssText;
		// clean and remove duplicate styles
		style = style.replace(/\s*(:|;|,|\(|\))\s*/g, '$1');
		style = style.replace(/\s+/g, ' ');
		style = style.split(';').unique().join(';');
		// apply to tag
		items[j].setAttribute('style',  style);
		
		// console.log('style applied', items[j]);
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment