Intro To Cascading Style Sheets
Volume Number: 14
Issue Number: 6
Column Tag: WebTech
Introduction to Cascading Style Sheets
by Paola Aliverti
Contributing Editor Tantek Çelik
HTML authoring has just gotten easier: style sheets land on
the Web
History
Cascading Style Sheets have been sporadically seen on the web for a while. It isn't until
recently, with the latest versions of Microsoft Internet Explorer and Netscape
Navigator, that they can be more widely appreciated. Style sheets on the Web work
pretty much like style sheets in a word processor, or in a desktop publishing
application. You can define a style called 'note' with blue text, enclosed in a border,
with 24pt type set. If you need to make visual changes at a later date, all you need to do
is change the defined style, without going through all the text in a page, or all the
pages. CSS allows you to establish a set of rules to apply throughout the document, or,
in our case, a site. Just like word-processing style sheets, Cascading Style Sheets on
the Web help in a more consistent and time-saving preparation of your documents, and
in styling and formatting of your documents.
The W3 Consortium has so far come up with the first list of specifications (CSS1), and
is working on the second series of specs. Both Netscape 4.0 and Internet Explorer 4.0
support most of the CSS1 specs. Authoring tools are currently on the market to help
you with CSS (Macromedia Dreamweaver, and Cascade, for example). You can find
up-to-date information about the current CSS standards on the Web Consortium web
site, at: http://www.w3.org/Style/CSS/.
HTML was designed for structure, not for style and formatting. That's why solutions
like frames, and tables came along. The problem is that both of those solutions are
neither straightforward nor consistent. Frames cause problems with bookmarks, and
tables bloat code and promote inflexible formats.
Tables and frames will not disappear from everyday use, but style sheets will make
your life much easier. If you are a web author, there will no longer be a need for
tables hacks, spacer GIFs, or text-based GIFs. Style sheets allow for easy maintenance
of your site, easier design, and improved control over the page layout. They help build
scalable sites, uniform sites with a consistent look among browsers and platforms. If
you are a web user, surfer, or cybernaut, you will like style sheets because the pages
are smaller, your downloads faster, and the layout 'spiffier'. You will also like the
browser scalability.
CSS allows you to re-define the look of HTML tags, add your own styling to them, or
create new Classes with new characteristics.
For example, you can decide to have non-underlined links:
non-underlined
link
Or to have a blue

tags:

H1 blue

Or place a dotted border around a paragraph:

paragraph with dotted border

NB: If you are among those who have not closed their

tags, it's time to start.

Browsers behave much more predictably when you close the tags properly!
The basics
How does style sheet code work? Let's start with some basic terminology. In a style
sheet code, there is a selector and a declaration.
A:link { text-decoration: none }
A:link is the selector, and
{ text-decoration: none } is the style declaration
The style declaration has a property (in this case 'text-declaration'), and a value
('none'). The selector can be a tag, or a newly-defined class. More specifics on
different selectors can be found in the CSS1 recommendation:
http://www.w3.org/pub/WWW/TR/REC-CSS1.
Of course, even though the CSS1 properties are defined by the official spec, not all
CSS-savvy browsers support all CSS1 properties. For a list of what is supported by
Navigator and Explorer, you can look at:
http://www.webreview.com/guides/style/
http://www.pcwebopedia.com/CSS.htm
http://webreference.internet.com/html/css.html
They are not always up-to-date, but they are the best I've found so far.
There are different ways to add style sheets to your HTML code:
• Embedding a Style Sheet
• Linking to External Style Sheet
• Importing an External Style Sheet
• Adding Styles Inline
The above-mentioned examples (except the A:link example) are all inline styles. All
you need to do is add the STYLE attribute to the tag you want to modify, and specify a
properties and values.
If you are looking at CSS not only for styling, but for efficient site management, you
don't want to be repeating the style for each instance of each tag. Let's take a look at
other ways to implement style sheets...
Embedded Style Sheets
You can add your CSS code at the beginning of each HTML file you want to affect, by
putting the following inside your HEAD (in your HTML silly!!!)
embedded.html
Welcome to the fruit factory!

Welcome

You will find the latest and greatest news on

HREF="topo.html">this page!

Remember to hide the content of your style sheets from the old browsers with the
HTML comment tag, as older browsers will ignore the tags, but
not the text in between.
Notice that different property/value pairs for the same selector should be separated
by a semicolon ";".
External Style Sheet
This is my favorite implementation of CSS, as it allows you to style several files in
your site, and update them by changing only one file. You can create separate external
files for the different sections of your web site. A file called 'eggplant.css' can define
the look and feel of the pages in all the sections of 'eggplant.com' site.
eggplant.css
H1 {color: blue}
A:link {text-decoration: none;
color: green;
font-size: larger;
font-weight: bold}
P {border: dotted blue;
text-align: center}
In the 'eggplant.com' site's pages, I will have the following code in the to link to
the 'eggplant.css' style sheet:
external.html
Welcome to the fruit factory!<TITLE></span></div><div class="chunk"><span class="style10"><LINK REL=stylesheet HREF="eggplant.css" TYPE="text/css"></span></div><div class="chunk"><span class="style10"></HEAD></span></div><div class="chunk"><span class="style10"><BODY></span></div><div class="chunk"><span class="style10"><H1>Welcome</H1></span></div><div class="chunk"><span class="style10"><P>You will find the latest and greatest news on <A</span></div><div class="chunk"><span class="style10">HREF="news.html">this page</A>!</span></div><div class="chunk"><span class="style10"></P></span></div><div class="chunk"><span class="style10"></BODY></span></div><div class="chunk"><span class="style10"></HTML></span></div><div class="chunk"><span class="style2">Importing an External Style Sheet</span></div><div class="chunk"><span class="style0">Let's say that Eggplant is partnering with TopoCo. in a sale of Topo Mouse dolls, and I</span></div><div class="chunk"><span class="style0">need to add TopoCo.'s traditional style to my Eggplant site. I can do this by adding to my</span></div><div class="chunk"><span class="style0">previously-mentioned 'eggplant.css' file one line of code: @import url(topo.css)</span></div><div class="chunk"><span class="style10">import.css</span></div><div class="code-block"><div class="chunk"><span class="style10">H1 {color: blue}</span></div><div class="chunk"><span class="style10">A:link {text-decoration: none}</span></div><div class="chunk"><span class="style10">P {border: dotted blue}</span></div></div><div class="chunk"><span class="style10">@import url(topo.css)</span></div><div class="chunk"><span class="style0">You can import as many style sheets as you like (but beware of possible conflicts, as</span></div><div class="chunk"><span class="style0">the next sections explain...). There are already collections of style sheets available on</span></div><div class="chunk"><span class="style0">the web </span><span class="style11">http://www.microsoft.com/gallery/files/styles</span><span class="style0">, and expect more in the</span></div><div class="chunk"><span class="style0">future. Importing style sheets can come pretty handy when you don't feel like creating</span></div><div class="chunk"><span class="style0">the files yourself. Of course, you should be aware not only of the legal implications of</span></div><div class="chunk"><span class="style0">taking someone else's work, and use it in your own site, but also of the stability of the</span></div><div class="chunk"><span class="style0">site you are linking to.</span></div><div class="chunk"><span class="style0">As far as I can tell, though, it's something you don't have to worry about, yet, because</span></div><div class="chunk"><span class="style0">only one version of the common browsers supports imported style sheets (Internet</span></div><div class="chunk"><span class="style0">Explorer 4.0 for the Mac).</span></div><div class="chunk"><span class="style2">Order of importance</span></div><div class="chunk"><span class="style0">As you probably already guessed from looking at the examples above, you can mix and</span></div><div class="chunk"><span class="style0">match any of the methods of implementation of CSS. Which one is more important? And</span></div><div class="chunk"><span class="style0">which one will prevail, in case two of them conflict? Although many references</span></div><div class="chunk"><span class="style0">attempt to explain (see comments about CSS1, and CSS2 specs in the next section), the</span></div><div class="chunk"><span class="style0">correct order of importance is the following:</span></div><div class="chunk"><span class="style0">1. Inline Styles.</span></div><div class="chunk"><span class="style0">2. Embedded, Linked, and Imported Style Sheets.</span></div><div class="chunk"><span class="style0">3. User preferences.</span></div><div class="chunk"><span class="style0">4. Browser's default settings.</span></div><div class="chunk"><span class="style0">Now let's move on to the next section to find out what prevails when styles conflict.</span></div><div class="chunk"><span class="style4">Cascading Abilities, Inheritance, Conflicts</span></div><div class="chunk"><span class="style0">As you probably already guessed from looking at the examples above, browsers need</span></div><div class="chunk"><span class="style0">firm rules of cascading and inheritance for different style sheets, or implementations</span></div><div class="chunk"><span class="style0">thereof, in order to avoid chaos. The specs of CSS1 differ a bit from CSS2 in this</span></div><div class="chunk"><span class="style0">matter. According to my research, browsers have already started to support CSS2</span></div><div class="chunk"><span class="style0">rules. I will skip the CSS1 rules, and just discuss the CSS2 cascade rules, which,</span></div><div class="chunk"><span class="style0">apart from being the latest, also seem more logical. Here is the first set of rules:</span></div><div class="chunk"><span class="style0">1. Follow specific declarations, or, if there aren't any, inherit values.</span></div><div class="chunk"><span class="style0">2. Sort declarations by importance.</span></div><div class="chunk"><span class="style0">3. Sort by specificity of selector.</span></div><div class="chunk"><span class="style0">4. Finally, among selectors of equal specificity, the latest onewins.</span></div><div class="chunk"><span class="style0">As most of the current versions of CSS browsers do not support factor 2 (the</span></div><div class="chunk"><span class="style0">'important' modifier), I will concentrate on the cascading declarations and inheritance.</span></div><div class="chunk"><span class="style0">The first rule can be divided in two simple rules:</span></div><div class="chunk"><span class="style0">1. Cascading takes precedence over inheritance.</span></div><div class="chunk"><span class="style0">2. Follow the order in which the styles appear, considering the latest</span></div><div class="chunk"><span class="style0">(closest to the text to which it refers) style the most important.</span></div><div class="chunk"><span class="style0">Let's take a look at what cascading and inheritance mean.</span></div><div class="chunk"><span class="style2">Cascading declarations and inheritance</span></div><div class="chunk"><span class="style10">inherit.html</span></div><div class="chunk"><span class="style10"><HTML></span></div><div class="backlinks"><div class="backlinks-title">Referenced by (5):</div><ul class="backlinks-list"><li><a href="0.html">Vol 14 Issues</a></li><li><a href="../MacTech Index/73.html">Authors (MacTech Index)</a></li><li><a href="../MacTech Index/27.html">H Topics (MacTech Index)</a></li><li><a href="../MacTech Index/15.html">Vol 14 Issues (MacTech Index)</a></li><li><a href="../MacTech Vol 14-1998/0.html">Vol 14 Issues (MacTech Vol 14-1998)</a></li></ul></div></div><script> let crossrefData = null; const searchInput = document.getElementById('search-input'); const searchResults = document.getElementById('search-results'); let selectedIndex = -1; let currentResults = []; // Load crossref data on first search async function loadCrossrefData() { if (crossrefData !== null) return; try { const response = await fetch('../crossref.json'); crossrefData = await response.json(); } catch (e) { crossrefData = []; console.error('Failed to load crossref.json:', e); } } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } function highlightMatch(text, query) { if (!query) return escapeHtml(text); const escaped = escapeHtml(text); const regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi'); return escaped.replace(regex, '<span class="highlight">$1</span>'); } async function search(query) { if (!query || query.length < 2) { searchResults.classList.remove('visible'); currentResults = []; return; } await loadCrossrefData(); const lowerQuery = query.toLowerCase(); currentResults = crossrefData.filter(item => item.name.toLowerCase().includes(lowerQuery) ).slice(0, 50); currentResults.sort((a, b) => { const aLower = a.name.toLowerCase(); const bLower = b.name.toLowerCase(); const aExact = aLower === lowerQuery; const bExact = bLower === lowerQuery; const aStarts = aLower.startsWith(lowerQuery); const bStarts = bLower.startsWith(lowerQuery); if (aExact && !bExact) return -1; if (bExact && !aExact) return 1; if (aStarts && !bStarts) return -1; if (bStarts && !aStarts) return 1; return a.name.localeCompare(b.name); }); if (currentResults.length === 0) { searchResults.innerHTML = '<div class="search-result"><span class="name">No results found</span></div>'; } else { searchResults.innerHTML = currentResults.map((item, idx) => ` <div class="search-result${idx === selectedIndex ? ' selected' : ''}" data-index="${idx}"> <div class="name">${highlightMatch(item.name, query)}</div> <div class="location">${escapeHtml(item.db)}</div> </div> `).join(''); } searchResults.classList.add('visible'); selectedIndex = -1; } function navigateToResult(index) { if (index >= 0 && index < currentResults.length) { const item = currentResults[index]; window.location.href = '../' + encodeURIComponent(item.db) + '/' + item.page + '.html'; } } function updateSelection() { const items = searchResults.querySelectorAll('.search-result'); items.forEach((item, idx) => { item.classList.toggle('selected', idx === selectedIndex); }); if (selectedIndex >= 0 && items[selectedIndex]) { items[selectedIndex].scrollIntoView({ block: 'nearest' }); } } searchInput.addEventListener('input', (e) => { search(e.target.value); }); searchInput.addEventListener('keydown', (e) => { if (e.key === 'ArrowDown') { e.preventDefault(); if (selectedIndex < currentResults.length - 1) { selectedIndex++; updateSelection(); } } else if (e.key === 'ArrowUp') { e.preventDefault(); if (selectedIndex > 0) { selectedIndex--; updateSelection(); } } else if (e.key === 'Enter') { e.preventDefault(); if (selectedIndex >= 0) { navigateToResult(selectedIndex); } else if (currentResults.length > 0) { navigateToResult(0); } } else if (e.key === 'Escape') { searchResults.classList.remove('visible'); selectedIndex = -1; } }); searchResults.addEventListener('click', (e) => { const result = e.target.closest('.search-result'); if (result && result.dataset.index !== undefined) { navigateToResult(parseInt(result.dataset.index)); } }); document.addEventListener('click', (e) => { if (!e.target.closest('.search-box')) { searchResults.classList.remove('visible'); } }); searchInput.addEventListener('focus', () => { if (searchInput.value.length >= 2) { search(searchInput.value); } }); </script></body></html>