How to Style XML Documents With CSS

HTML and CSS Code in an IDE Environment

Boskampi/Pixabay/Creative Commons

Creating an XML document, writing the DTD, and parsing it with a browser is all fine, but how will the document display when you view it? XML is not a language of presentation. Documents written with XML will have no formatting at all.

How to View XML

The key to viewing XML in a browser is Cascading Style Sheets. Style sheets allow you to define every aspect of your XML document, from the size and color of your text to the background and position of your non-text objects.

Say you have an XML document:




]>


Judy
Layard
Jennifer
Brendan


If you were to view that document in an XML ready browser, such as Internet Explorer, it would display something like this:

Judy Layard Jennifer Brendan

But what if you wanted to differentiate between the parent and child elements? Or even make a visual distinction between all the elements in the document. You can't do that with XML, and it is not a language that is meant to be used for display.

Styling XML

But luckily, it is easy to use Cascading Style Sheets, or CSS, in XML documents to define how you want those documents and applications to display when viewed in a browser. For the above document, you can define the style of each of the tags in the same way you would an HTML document.

For example, in HTML you might want to define all text within paragraph tags (

p {
font-family : verdana, geneva, helvetica;
background-color : #00ff00;
}

The same rules work for XML documents. Each tag in XML can be defined in the XML document:

family {
color : #000000;
}

parent {
font-family : Arial Black;
color : #ff0000;
border : solid 5px;
width : 300px;
}

child {
font-family : verdana, helvetica;
color : #cc0000;
border : solid 5px;
border-color : #cc0000;
}

Once you have your XML document and your stylesheet is written, you need to put them together. Similar to the link command in HTML, you put a line at the top of your XML document (below the XML declaration), telling the XML parser where to find the stylesheet. For example:



As stated above, this line should be found below the declaration but before any of the elements in the XML document.

Putting it all together, your XML document would read:





]>


Judy
Layard
Jennifer
Brendan


Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Style XML Documents With CSS." ThoughtCo, Jul. 31, 2021, thoughtco.com/styling-xml-docs-with-css-3471383. Kyrnin, Jennifer. (2021, July 31). How to Style XML Documents With CSS. Retrieved from https://www.thoughtco.com/styling-xml-docs-with-css-3471383 Kyrnin, Jennifer. "How to Style XML Documents With CSS." ThoughtCo. https://www.thoughtco.com/styling-xml-docs-with-css-3471383 (accessed March 19, 2024).