How to Use XML With CSS

XML and CSS work well together

Close up of XML code

kr7ysztof / Getty Images

If you're familiar with how CSS styles HTML pages, you'll appreciate the concept of formatting. At the onset of the XML markup language, displaying data was a bit complicated, but that changed with style sheets. 

By adding a stylesheet reference, you can format and display your XML code as a web page. Without CSS or some other formatting, XML appears as basic text with an error that states that the browser could not find a formatting document.

XML Styling

A simple style sheet only requires that you list the element and the formatting attributes necessary to display the data.

The first line of the formatting file is the root element. The attributes for the root apply to the whole page, but you change them for each tag. This means you can designate the background color for the page and then again for each section.

Save your file to the same directory as your XML file, and make sure it has the .CSS file extension. 

Link to the CSS From the XML

At this point, these are two wholly separate documents. The processor has no idea that you want them to work together to create a web page.

You can fix this by adding a statement to the top of the XML document that identifies the path to the CSS file. The statement goes directly under the initial XML declaration statement.