Creating XML Style Sheets With CSS

By Daniel Imbellino
Feb 28, 2013

Can I build XML webpage’s just like with HTML? The simple answer, yes! However there are a few things to note here. For one, unlike HTML and XHTML, XML elements have no default formatting characteristics. We can use CSS to build internal or external style sheets for our XML documents. However, we must explicitly declare our box model display properties since they are not predefined for us, as is the case with other standardized markup languages. There are a number of ways to define how our content should be formatted within our CSS styles, either way we need specify this formatting as either “block level” (an element starts at the beginning of a new line), or “inline” (an element is formatted within a line itself). The preferred formatting for XML pages is to display all elements as “block level.” Displaying an element inline will cause it to be displayed after its preceding element (on the next line). Block level formatting is better since all elements are displayed independently of each other. First we need to declare our style sheet from within our XML document like so:

<?xml version =”1.0”?>

<?xml-stylesheet type=”text/css” href=”location-of-your-css-stylesheet.css” ?>

Followed by your XML markup… Now you can open your text editor and name your file, remembering to save your document using the .css file extension. Here we will declare our elements as “block level” within our CSS document using our fictitious XBOX markup language, and create styles for our elements using CSS ID’s: First declare your element:

heading {display: block; width: 600px; height: 60px; position: absolute; left: 20%; top: 10%; font-size: 55px; font-family: arial, Helvetica, times new roman; text-align: center; }

Since we declared our heading tag in our CSS and linked our XML document to our external CSS style sheet, we can now add the styles we defined and reference them to our “heading” element within our XML page: page heading goes here

It’s really that simple! If our document was about XBOX 360 video games, we could create a set of elements that are descriptive of this content, something we cannot do with HTML:

<heading>Heading Goes Here</heading>
<model type=”360” />

Now we could simply define style information for our elements, using whatever fonts, layout, etc, we choose. For more information about creating style sheets for both XML and HTML markup languages, check out our tutorials on Working With CSS