Applying User Styles

submited by
Style Pass
2021-06-07 01:00:04

In the last chapter, we gave each pre element a gray background. It looks OK, and it is good to have defaults… but of course sites wants a say in how they look. Web sites do that with Cascading Style Sheets, which allow web authors (and, as we’ll see, browser developers) to define how a web page ought to look.

One way a web page can change its appearance is with the style attribute. For example, this changes an element’s background color:

More generally, a style attribute contains property/value pairs separated by semicolons. The browser looks at those property-value pairs to determine how an element looks, for example to determine its background color.

To add this to our browser, we’ll need to start by parsing these property/value pairs. I’ll use recursive parsing functions, which are a good way to build a complex parser step by step. The idea is that each parsing function advances through the text being parsed and returns the data it parsed. We’ll have different functions for different types of data, and organize them in a CSSParser class that stores the text being parsed and the parser’s current position in it:

Whitespace is insignificant, so there’s no data to return in this case. On the other hand, we’ll want to return property names and values when we parse them:

Leave a Comment