How to Use XML With CSS

Photographer Editing Photos on her computer.
vgajic / 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 style sheet 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 Example

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

This bit of code tells the processor which elements to display and how they should look on the web page, like this:

sample {background-color: #ffffff; width: 100%;}

mymessage {display: block; background-color: #999999; margin-bottom: 30pt;}

body {font-size: 50%} 

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 this 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, like this:

<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/css" href="products.css"?>

In this example, the CSS file is called products.css, which is why it's labeled as such in the XML document.

Change that to whatever file name you chose for the CSS file.

Format
mla apa chicago
Your Citation
Ferrara, Darla. "How to Use XML With CSS." ThoughtCo, Jan. 13, 2018, thoughtco.com/display-xml-on-web-page-3466588. Ferrara, Darla. (2018, January 13). How to Use XML With CSS. Retrieved from https://www.thoughtco.com/display-xml-on-web-page-3466588 Ferrara, Darla. "How to Use XML With CSS." ThoughtCo. https://www.thoughtco.com/display-xml-on-web-page-3466588 (accessed February 18, 2018).