0

I'm trying to get a regular expression (in Javascript) to get margin, padding and border values, reading them from document.styleSheets

I wrote that:

/:\s*?(\d+)(px)?/gi

but is not good. The main problem is the the rule should be like:

margin: 3px;
margin: 3px 2px;
margin: 3px 2px 1px;
margin: 3px 2px 1px 0;
margin-top: 3px;
margin-right: 3px;
margin-left: 3px;
margin-bottom: 3px;

the same for the padding. For the border is similar:

border: 1px solid #000;
border-width: 1px 1px 2px 0;
border-top-width: 1px;
border-left-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-top: 1px solid #000;
border-left: 1px solid #000;
border-right: 1px solid #000;
border-bottom: 1px solid #000;

I can split the rule and search for each type, something like

if(rule.indexOf('margin') > -1) {
    ...
} else if (rule.indexOf('margin-top') > -1) {
    ...
}

and use different regex .. but I would like to have the more general regex to avoid a long list of "if".

Can anybody help me?

Many thanks, da

5
  • 4
    Have you considered using a CSS parser? Commented Dec 10, 2012 at 10:53
  • Don't forget to take into account that some developers don't always use pixel positioning. You should check for; - em - % - px Commented Dec 10, 2012 at 10:59
  • Of course, there is also this variable :( Commented Dec 10, 2012 at 11:26
  • What do you mean with CSS parser? Commented Dec 10, 2012 at 11:26
  • I mean a library that can parse CSS without the hackery of using regexes. Commented Dec 10, 2012 at 11:29

1 Answer 1

0

As the stylesheets can be formatted in several different ways, you should have a look at other alternatives, like the JSizes jQuery extension plugin that will be very helpful to get those values.

Sign up to request clarification or add additional context in comments.

1 Comment

My problem is exactly that I want to avoid the use of jQuery, because jQuery works on DOM elements and I want to get the total size of an element (what in jQuery is easily done with offsetWidth), before creating the DOM, my porpouse is to improve the performance (even if I'm not so sure that my solution is good)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.