Is it possible to run on the server-side the same process that browsers run in order to apply CSS to the DOM?
For example, could I take a HTML document, apply all the CSS rules (linked, embedded and inline) to work out for any element its attributes. I’m mostly concerned about the box model (i.e. its position, margin, border and padding).
The only way I can think of so far is to use Selenium RC and jQuery to pass the values back. However, this seems very resource-intensive, so I’m wondering if there’s another way. I’ve looked around Google and searches for ‘parsing CSS’ only bring results for reading individual styles, not applying all CSS rules it to the whole DOM and then working out the results.
Any language will do.
Example (not the real use case, but a similar one)
You’re building an API which allows people who know HTML and CSS to generate Java GUIs. The API allows the developer to pass in their HTML, and it then returns back all the code to construct the GUI, with the same sizes and positions for all the elements.
Start by reading this document on how browsers work to realize that to calculate something like that requires a layout engine. Things like the dimensions of rendered fonts and images, as well as the box model with its complex rules for margin collapsing, and more all influence the final layout.
Unless you can host a layout engine (like WebKit) in your server-side application you are looking at implementing a layout engine, minus the actual painting to screen, just to establish the layout of your application (if I understand your requirements correctly).
Having said that, the WebKit engine is used in a lot of projects, but most of them are browsers or other client-side software. A quick search on Google did turn up one interesting result:
If you can’t host an existing layout engine, there may be some HTML-like (XML) UI layout technologies available. perhaps those are a better option? E.g. Microsoft’s Silverlight/XAML, Adobe’s MXML (supports some CSS rules as well), UIML, or Mozilla’s XUL.