Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse CSS font shorthand format

Tags:

javascript

css

I need to parse the CSS font shorthand format into the separate components (font-family, font-size, font-weight, ...). This shorthand format looks pretty complicated. Here are two examples:

10px sans-serif
bold italic small-caps 1em/1.5em verdana,sans-serif

Before I start writing a parser for it, is there an already existing parser out there I could use (Preferably written in JavaScript)?

like image 660
kayahr Avatar asked Apr 11 '11 08:04

kayahr


People also ask

What is font shorthand property in CSS?

The font CSS shorthand property sets all the different properties of an element's font. Alternatively, it sets an element's font to a system font.

Which is the correct order for font shorthand property?

5.5 CSS font shorthand The font property regroups (in this particular order): font-style. font-variant. font-weight.

Which font property is specified at last in font shorthand?

The CSS Font Property The font property is a shorthand property for: font-style. font-variant.


2 Answers

Here's a "temporary DOM element and using jquery's css() function" solution:

http://jsfiddle.net/thirtydot/tpSsE/2/

var $test = $('<span />');
$test.css('font', 'bold italic small-caps 1em/1.5em verdana,sans-serif');

alert($test.css('fontWeight'));
alert($test.css('fontStyle'));
alert($test.css('fontVariant'));
alert($test.css('fontSize'));
alert($test.css('lineHeight'));
alert($test.css('fontFamily'));

like image 67
thirtydot Avatar answered Oct 02 '22 23:10

thirtydot


Pure free-range Javascript version:

var parsedStyleForCSS = function(cssString){
    var el = document.createElement("span");
    el.setAttribute("style", cssString);

    return el.style; // CSSStyleDeclaration object
};

var parsedStyle = parsedStyleForCSS("font: bold italic small-caps 1em/1.5em verdana,sans-serif");

console.log(parsedStyle["fontWeight"]); // bold
console.log(parsedStyle["fontStyle"]); // italic
console.log(parsedStyle["fontVariant"]); // small-caps
console.log(parsedStyle["fontSize"]); // 1em
console.log(parsedStyle["lineHeight"]); // 1.5em
console.log(parsedStyle["fontFamily"]); // verdana, sans-serif

If you're looking to do something similar with complete stylesheets, see this answer: Parsing CSS in JavaScript / jQuery

like image 39
mattsven Avatar answered Oct 03 '22 00:10

mattsven