Cette traduction a été interrompue suite à l'annonce de la traduction par J.J. SOLARI à l'adresse suivante http://www.yoyodesign.org/doc/w3c/css1/index.html (Voir le message: http://lists.w3.org/Archives/Public/w3c-translators/2001JulSep/0025.html).
La version française de cette traduction est :
http://www.la-grange.net/w3c/REC-CSS1/
Traducteur : Karl Dubost - <karl+misc@la-grange.net>
La version française peut contenir des erreurs. La version anglaise de cette note est l'unique version
normative. Version originale : http://www.w3.org/TR/REC-CSS1
Note : J'ai modifié les exemples pour qu'ils soient en XHTML 1.0 Strict
REC-CSS1-19990111
Cette version : | http://www.w3.org/TR/1999/REC-CSS1-19990111 |
Dernière version : | http://www.w3.org/TR/REC-CSS1 |
Version précédente : | http://www.w3.org/TR/REC-CSS1-961217 |
Auteurs : |
Håkon Wium Lie (howcome@w3.org) Bert Bos (bert@w3.org) |
This document is a W3C Recommendation. It has been reviewed by W3C (http://www.w3.org/) Members and general consensus that the specification is appropriate for use has been reached. It is a stable document and may be used as reference material or cited as a normative reference from another document. W3C promotes widespread deployment of this Recommendation.
A list of current W3C Recommendations and other technical documents can be found at http://www.w3.org/TR/.
This document is a revised version of the document first released on 17 December 1996. Changes from the original version are listed in Appendix F. The list of known errors in this specification is available at http://www.w3.org/Style/CSS/Errata/REC-CSS1-19990111-errata
Ce document spécifie le niveau du mécanisme des feuilles de style imbriquées (CSS1). CSS1 est un mécanisme simple de feuille de style qui permet aux auteurs et aux lecteurs de donner du style (par exemple polices, couleurs et espace) aux documents HTML. Le langage CSS1 est intelligible et facile à écrire, et il exprime le style avec la même terminologie que les outils de publication.
Un des principes fondamentaux des CSS est que les feuilles de style sont imbriquées (elles cascadent) ; les auteurs peuvent attacher une feuille de style de personnelle pour ajuster le contenu à un certain handicap technologique ou humain. Les règles pour résoudre les conflits entre les feuilles de style comme définies dans la spécification.
Cette recommandation est le résultat des activités du W3C dans le domaine des feuilles de style. Pour en savoir plus sur les feuilles de style, voir [1].
Résumé
Terminologie
1
Concepts fondamentaux
1.1
Containment in HTML
1.2
Groupage
1.3
Inheritance
1.4
Class en tant que sélecteur
1.5
ID en tant que sélecteur
1.6
Sélecteurs contextuels
1.7
Commentaires
2
Pseudo-classes et
pseudo-éléments
2.1
Anchor pseudo-classes
2.2
Typographical
pseudo-elements
2.3
The 'first-line'
pseudo-element
2.4
The 'first-letter'
pseudo-element
2.5
Pseudo-elements in
selectors
2.6
Multiple
pseudo-elements
3
The cascade
3.1
'important'
3.2
Cascading order
4
Formatting model
4.1
Block-level elements
4.1.1
Vertical formatting
4.1.2
Horizontal formatting
4.1.3
List-item elements
4.1.4
Floating elements
4.2
Inline elements
4.3
Replaced elements
4.4
The height of lines
4.5
The canvas
4.6
'BR' elements
5
CSS1 properties
5.1
Notation for property
values
5.2
Font properties
5.2.1
Font matching
5.2.2
'font-family'
5.2.3
'font-style'
5.2.4
'font-variant'
5.2.5
'font-weight'
5.2.6
'font-size'
5.2.7
'font'
5.3
Color and background
properties
5.3.1
'color'
5.3.2
'background-color'
5.3.3
'background-image'
5.3.4
'background-repeat'
5.3.5
'background-attachment'
5.3.6
'background-position'
5.3.7
'background'
5.4
Text properties
5.4.1
'word-spacing'
5.4.2
'letter-spacing'
5.4.3
'text-decoration'
5.4.4
'vertical-align'
5.4.5
'text-transform'
5.4.6
'text-align'
5.4.7
'text-indent'
5.4.8
'line-height'
5.5
Box properties
5.5.1
'margin-top'
5.5.2
'margin-right'
5.5.3
'margin-bottom'
5.5.4
'margin-left'
5.5.5
'margin'
5.5.6
'padding-top'
5.5.7
'padding-right'
5.5.8
'padding-bottom'
5.5.9
'padding-left'
5.5.10
'padding'
5.5.11
'border-top-width'
5.5.12
'border-right-width'
5.5.13
'border-bottom-width'
5.5.14
'border-left-width'
5.5.15
'border-width'
5.5.16
'border-color'
5.5.17
'border-style'
5.5.18
'border-top'
5.5.19
'border-right'
5.5.20
'border-bottom'
5.5.21
'border-left'
5.5.22
'border'
5.5.23
'width'
5.5.24
'height'
5.5.25
'float'
5.5.26
'clear'
5.6
Classification
properties
5.6.1
'display'
5.6.2
'white-space'
5.6.3
'list-style-type'
5.6.4
'list-style-image'
5.6.5
'list-style-position'
5.6.6
'list-style'
6
Units
6.1
Length units
6.2
Percentage units
6.3
Color units
6.4
URL
7
CSS1 conformance
7.1
Forward-compatible
parsing
8
Références
9
Remerciements
Appendix A: Sample style sheet for HTML 2.0
Appendix B: CSS1 grammar
Appendix C: Encoding
Appendix D: Gamma correction
Appendix E: The applicability and extensibility of CSS1
Appendix F: Changes from the 17 December 1996 version
Dans le texte de cette spécification, les guillemets simples ('...') indiquent les extraits HTML et CSS.
Il est très facile de créer une feuille de style simple. Il n'est nécessaire de connaître que quelques rudiments de HTML et avoir quelques bases de terminologie du monde de la publication. E.g., pour définir la couleur du texte de l'élément 'H1' en bleu, on peut dire :
H1 { color: blue }
L'exemple précédent est une règle CSS simple. Une règle est faite de deux parties principales : sélecteur ('H1') et déclaration ('color: blue'). La déclaration a deux parties : propriété ('color') et valeur ('blue'). Alors que l'exemple précédent tente de modifier seulement une des propriétés nécessaires à l'affichage du document HTML, il définit une feuille de style en lui-même. Combiné avec d'autres feuilles de style (une fonctionnalité fondamentale de CSS est que les feuilles de styles peuvent être combinées), cela déterminera la présentation finale du document.
Le sélecteur est le lien entre le document HTML et la feuille de style, et tous les types d'élément HTML sont potentiellement des sélecteurs. Les types d'élément HTML sont définis dans la spécification HTML [2].
La propriété 'color' est une de la cinquantaine de propriétés qui détermine la présentation d'un document HTML. La liste des propriétés et de leurs valeurs possibles est définie dans cette spécification.
Les auteurs HTML ont besoin d'écrire des feuilles de style uniquement s'il veulent définir un style spécifique pour leurs documents. Chaque agent utilisateur (UA, souvent un "navigateur web" ou un "client web") aura une feuille de style par défaut qui présente les documents d'une façon raisonnable -- mais surement assez commune --. L'appendice A contient une feuille de style d'exemple pour présenter les documents HTML tels que suggérés dans la spécification HTML 2.0 [3].
La grammaire formelle du langage CSS1 est définie dans l'appendice B.
Afin que les feuilles de style puissent modifier la présentation, l'AU doit être informé de leurs existence. La spécification HTML [2] définit la façon de lier HTML à des feuilles de style. Cette section est bien sûr informative et non normative :
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>title</title> <link rel="STYLESHEET" type="text/css" href="http://style.com/cool" title="Cool" /> <style type="text/css"> @import url(http://style.com/basic); H1 { color: blue } </style> </head> <body> <h1>Headline is blue</h1> <p style="color: green">While the paragraph is green.<p> </body> </html>
L'exemple montre 4 façons de combiner le style et le HTML : en utilisant l'élément 'LINK' pour pointer sur une feuille de style externe, un élément 'STYLE' dans l'élément 'HEAD', une feuille de style importé en utilisant la notation CSS '@import' et un attribut 'style' dans un élément à l'intérieur de 'BODY'. La dernière option mélange le style avec le contenu et ainsi perd les avantages habituels des feuilles de style traditionnelles.
l'élément 'LINK' référence les feuilles de style alternative que le lecteur peut sélectionner, alors que les feuilles de style importées sont automatiquement mélangées avec le reste de la feuille de style.
Traditionnellement, les AUs ignorent toutes balises inconnues. Ceci a pour conséquence, les vieux AUs ignoreront l'élément 'STYLE', mais son contenu sera traité comme faisant partie du corps du document, et affiché comme tel. Pendant la période de transition, le contenu de l'élément 'STYLE' peut être caché en utilisant les commentaires SGML :
<style type="text/css"><!-- H1 { color: green } --></style>
Comme l'élément 'STYLE' est déclaré avec le type "CDATA" dans la DTD (tel que défini en [2]), les parseurs SGML conformes n'interprêteront pas la feuille de style précédente comme un commentaire devant être effacé.
POur réduire la taille des feuilles de style, il est possible de regrouper les sélecteurs en une liste séparée par des virgules :
H1, H2, H3 { font-family: helvetica }
De la même manière, les déclarations peuvent être groupées :
H1 { font-weight: bold; font-size: 12pt; line-height: 14pt; font-family: helvetica; font-variant: normal; font-style: normal; }
De plus, certaines propriétés ont leur propre syntaxe de groupage :
H1 { font: bold 12pt/14pt helvetica }
qui est équivalent à l'exemple précédent.
Dans le premier exemple, bleu (blue) est la couleur des éléments. Supposez qu'il existe un élément 'H1' avec un élément mis en valeur à l'intérieur :
<h1>L'entête <em>est</em> important !</h1>
Si aucune couleur n'a été attribué à l'élément 'EM', la partie mise en valeur "est" héritera de la couleur de l'élément parent, i.e. il appara√Ætra en bleu. D'autres propriétés de style possèdent également ce mécanisme d'héritage, e.g. 'font-family' and 'font-size'.
Pour définir la propriété de style "par défaut", il est possible de définir la propriété d'un élément pour lequel tous les autres éléments sont des enfants. Dans les documents HTML, l'élément 'BODY' peut remplir cette fonction :
BODY { color: black; background: url(texture.gif) white; }
Ceci fonctionnera même si l'auteur a omis la balise 'BODY' (ce qui est autorisé) puisque le parseur HTML inférera la balise manquante. L'exemple précedent définit la couleur du texte par la couleur noire et le fond par une image. Le fond sera blanc si l'image n'est pas disponible. (Voir section 5.3 pour en savoir plus.)
Certaines propriétés de style ne sont pas héritées de l'élément parent vers l'élément enfant. La plupart du temps, la raison est intuitive. E.g., la propriété 'background' n'hérite pas, mais les fonds des éléments parents seront tout de même présents par défaut.
Souvent, la valeur d'une propriété est un pourcentage qui se réferre à une autre propriété :
P { font-size: 10pt } P { line-height: 120% } /* relatif à 'font-size', i.e. 12pt */
Pour chaque propriété qui permet les valeurs en pourcentage, il est défini à quelle propriété elles peuvent s'appliquer. Les éléments enfants de 'P' hériteront des valeurs calculées de 'line-height' (i.e. 12pt), non du pourcentage.
Pour augmenter la granularité de contr√¥le sur les éléments, un nouvel attribut a été ajouté à HTML [2]: 'CLASS'. Tous les éléments à l'intérieur de l'élément 'BODY' peuvent être "classés", et la classe peut être traitée dans la feuille de style :
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Titre</title> <style type="text/css"> H1.pastoral { color: #00FF00 } </style> </head> <body> <h1 class="pastoral">Chemin trop vert</h1> </body> </html>
Les règles normales d'héritage s'appliquent aux éléments classés ; ils héritent des valeurs de leur parent dans la structure du document.
Il est possible de traiter tous les éléments d'une même classe en omettant le nom de la balise dans le sélecteur :
.pastoral { color: green } /* tous les éléments avec CLASS pastoral */
Une unique classe peut être spécificié par le sélecteur. 'P.pastoral.marine' est un sélecteur invalide en CSS1. (Sélecteurs contextuels, décrits ci-dessous, peuvent avoir une classe par sélecteur simple.)
CSS donne tant de pouvoir à l'attribut CLASS que dans beaucoup de cas, l'importance de l'élément sur lequel la classe est spécifié est toute relative -- vous pouvez à peu près émuler le comportement de tout élément par un autre. Se reposer sur cette possibilité n'est pas recommandé, car cela détruit le niveau de structure qui a une signification universelle (éléments HTML). Une structure basée sur CLASS est uniquement utile dans le cadre de domaine restreint, où la signification d'une classe a été mutuellement décidée.
HTML [2] introduit également l'attribut 'ID' qui ne peut avoir qu'une valeur unique sur l'ensemble du document. Il peut être d'une importance particulière comme un sélecteur de feuille de style, et peut être traité avec un '#' précédant :
#z98y { letter-spacing: 0.3em } h1#z98y { letter-spacing: 0.5em } <p id="z98y">Texte large</p>
Dans l'exemple précédent, le premier sélecteur correspond à l'élément 'P' à cause de la valeur de l'attribut 'ID'. Le deuxième sélecteur spécifie dans le même temps un type d'élément et une valeur ID, et donc ne correspondra pas à l'élement 'P'.
En utilisant l'attribut ID comme sélecteur, il est possible de fixer les propriétés de style uniquement élément par élément. Alors que les feuilles de style ont été conçues pour enrichir la structure du document, cette fonctionnalité permettra aux auteurs de créer des documents qui soient bien présentés sur les canvas sans utiliser les avantages des éléments structurels de HTML. Cette utilisation des feuilles de style n'est pas conseillée.
La saisie des concepteurs CSS est allégée par le mécanisme d'héritage. Au lieu de spécifier toutes les propriétés de style, il est possible d'en créer un par défaut, et de lister ensuite les exceptions. pour donner aux éléments 'EM' à l'intérieur des 'H1' une couleur différente, il est possible de spécifier :
H1 { color: blue } EM { color: red }
Lorsque cette feuille de style est en action, toutes les sections mises en valeur (<em>...</em>) à l'intérieur ou à l'extérieur de 'H1' sera rouge. Il est probable que la personne veuille qu'uniquement les éléments 'EM' compris dans un élément 'H1' soit rouge. Ceci est possible en le précisant de la façon suivante :
H1 EM { color: red }
Le sélecteur est maintenant un motif de recherche sur la pile des éléments ouverts, et ce type de sélecteur s'appelle un sélecteur contextuel. les sélecteurs contextuels sont composés de plusieurs sélecteurs simples séparés par des espaces (tous les sélecteurs décrits jusqu'à maintenant étaient des sélecteurs simples). Uniquement les éléments qui correspondent au dernier sélecteur simple (dans ce cas l'élément 'EM') sont traités, et seulement si le motif de recherche correspond. Les sélecteurs contextuels dans CSS1 recherchent les relations parentales, bien que d'autres types de relations (e.g. parent-enfant) pourrait être introduites dans des versions ultérieures. Dans l'exemple précédent de 'H1', i.e. si 'EM' est à l'intérieur d'un élément 'H1'.
UL LI { font-size: small } UL UL LI { font-size: x-small }
Ici, le premier sélecteur correspond aux éléments 'LI' avec au moins un 'UL' parent. Le second sélecteur correspond à un sous-ensemble du premier, i.e. les éléments 'LI' avec au moins deux 'UL' parents. Le conflit est résolu par le second sélecteur à cause d'un motif de recherche plus long. Voir l'ordre de cascade (section 3.2) pour plus d'information sur ceci.
Les sélecteurs contextuels peuvent être définis en fonction des types d'éléments,des attributs CLASS, des attributs ID ou d'une combinaison de ces derniers :
DIV P { font: small sans-serif } .reddish H1 { color: red } #x78y CODE { background: blue } DIV.sidenote H1 { font-size: large }
Le premier sélecteur correspond à tous les éléments 'P' qui ont un 'DIV' comme parent. Le second sélecteur correspond à tous les éléments 'H1' qui ont un parent de classe 'reddish'. Le troisième sélecteur correspond à tous les éléments 'CODE' qui sont enfants d'un élément avec l'attribut 'ID="x78y"'. Le quatrième sélecteur correspond aux éléments 'H1' qui ont un parent DIC avec une classe 'sidenote'.
Plusieurs sélecteurs contextuels peuvent être groupés ensemble :
H1 B, H2 B, H1 EM, H2 EM { color: red }
Ce qui est équivalent à :
H1 B { color: red } H2 B { color: red } H1 EM { color: red } H2 EM { color: red }
Les commentaires textuels dans les feuilles de style CSS sont similaires à ceux du langage de programmation C [7] :
EM { color: red } /* rouge, vraiment rouge !! */
Les commentaires ne peuvent pas être imbriqués. Pour un parseur CSS1, un commentaire est équivalent à un espace.
En CSS1, le style est normalement relié à un élément basé sur sa position dans la structure du document. Ce modèle simple est suffisant pour une grande variété de styles, mais ne couvrent pas certains effets assez commun. Le concept de pseudo-classe et de pseudo-élément étent la notion d'adressage en CSS1 pour permettre à une information externe d'influencer le traitement de la mise en forme.
Les pseudo-classes et les pseudo-éléments peuvent être utilisées dans les sélecteurs CSS, mais n'existent pas dans le source HTML. Ils sont plutôt "insérés" par l'AU suivant certaines conditions afin d'être utilisés pour l'adressage dans les feuilles de style. On les appelle comme les "classes" et les "éléments" pusique c'est une manière simple de décrire leur comportement. Plus spécifiquement, leur comportement est défini par une séquence imaginaire de balise.
Les pseudo-éléments sont utilisés pour pointer des sous-parties d'éléments, alors que les pseudo-classes permettent aux feuilles de style de différencier entre différents types d'éléments.
Les agents utilisateurs affichent généralement les liens nouvellement visités différement des plus vieux. En CSS1, ceci est géré par les pseudo-classes attachées à l'élément 'A' :
A:link { color: red } /* liens non visités */ A:visited { color: blue } /* liens visités */ A:active { color: lime } /* liens actifs */
Tous les éléments 'A' avec un attribut 'HREF' seront placés dans un et seulement un de ces groupes (i.e. les ancres cibles ne sont pas concernées). Les AUs peuvent choisir de déplacer le statut d'un élément de 'visited' à 'link' après un certain temps. Un lien 'active' est un lien qui est en cours de sélection (e.g. par un clic sur bouton de la souris) par le lecteur.
Le formatage d'une pseudo-classe d'ancre est tel que si la classe avait été insérée manuellement. Un UA n'a pas l'obligation de reformater un document lors de son affichage dû aux transitions des pseudo-classes d'ancres. E.g., une feuille de style peut spécifier que le 'font-size' (taille de la police) d'un lien 'active' (activé) devrait être plus grand qu' un lien 'visited' (visité), mais l'AU n'a pas l'obligation de reformater dynamiquement le document quand le lecteur sélectionne le lien 'visited'.
Les sélecteurs de pseudo-classe ne correspondent pas aux classes normales et vice-versa. La règle de style dans l'exemple suivant n'aura aucun effet :
A:link { color: red } <a class="link" name="target5"> ... </a>
En CSS1, les pseudo-classes d'ancres n'ont pas d'effets sur les éléments autres que 'A'. Ainsi, le type d'élément peut être omis du sélecteur :
A:link { color: red } :link { color: red }
Les deux sélecteurs précédents sélectionneront le même élément en CSS1.
Les noms des pseudo-classes ne sont pas dépendants de la casse.
Les pseudo-classes peu être utilisés dans les sélecteurs contextuels :
A:link IMG { border: solid blue }
Il est également possible de combiner les pseudo-classes avec les classes normales :
A.external:visited { color: blue } <a class="external" href="http://example.com/">lien externe</A>
Si le lien dans l'exemple précédent a été visité, il sera affiché en bleu. Notez que les noms des classes normales précèdent les pseudo-classes dans le sélecteur.
Les effets typographiques les plus communs ne sont pas associés à des éléments structurels, mais plutôt aux éléments typographiques tels que formatés par le canvas. En CSS1, deux éléments typographiques peubent être traités grâce aux pseudo-éléments ; la première ligne d'un élément, et la première lettre.
noyau CSS1 (CSS1 core) : AUs peuvent à l'occasion ignorer toutes les règles avec ':first-line' ou ':first-letter' dans le sélecteur, ou, alternativement supporter uniquement un sous-ensemble des propriétés de ces pseudo-éléments.(voir la section 7)
Le pseudo-élément 'first-line' est utilisé pour appliquer un style spécifique à la première ligne telle qu'affichée sur le support :
<STYLE TYPE="text/css">
P:first-line { font-variant: small-caps }
</STYLE>
<p>La première ligne d'un article dans Newsweek.</p>
Dans un AU texte, ceci pourrait être formatté comme suit :
LA PREMIERE LIGNE d'un article dans Newsweek.
La séquence de balise fictive dans l'exemple ci-dessus :
<P> <P:first-line> La première ligne d'un </P:first-line> article dans Newsweek. </P>
La balise de fin 'first-line' est insérée à la fin de la première ligne comme formatté sur le support.
Le pseudo-élément 'first-line' peut seulement être attaché à un élément de type bloc.
Le pseudo-élément 'first-line' est similaire à un élément interne mais avec certaines restrictions. Seulement les propriétés suivantes s'appliquent à un élément 'first-line' : propriétés de police (5.2), propriétés de couleur et de fond d'écran (5.3), 'word-spacing' (5.4.1), 'letter-spacing' (5.4.2), 'text-decoration' (5.4.3), 'vertical-align' (5.4.4), 'text-transform' (5.4.5), 'line-height' (5.4.8), 'clear' (5.5.26).
Le pseudo-élément 'first-letter' est utilisé pour les lettrines (capitales en début de phrase) et petites majuscules qui sont des effets typographiques classiques. Le comportement est similaire à un élément interne si sa propriété 'float' est fixé à 'none', sinon le comportement est similaire à celui d'un élément flottant. Voici les propriétés qui s'appliquent aux pseudo-éléments 'first-letter' : propriétés de police (5.2), propriétés de couleurs et de fonds (5.3), 'text-decoration' (5.4.3), 'vertical-align' (seulement si 'float' est 'none', 5.4.4), 'text-transform' (5.4.5), 'line-height' (5.4.8), propriétés de marge (5.5.1-5.5.5), propriétés de marge interne (5.5.6-5.5.10), propriétés de bordure (5.5.11-5.5.22), 'float' (5.5.25), 'clear' (5.5.26).
Voici un exemple pour réaliser une lettrine qui s'étale sur 2 lignes :
<html> <head> <title>Titre</title> <style type="text/css"> P { font-size: 12pt; line-height: 12pt } P:first-letter { font-size: 200%; float: left } SPAN { text-transform: uppercase } </style> </head> <body> <p><span>Les premiers</span> mots d'un article dans Le Monde.</p> </body> </html>
Si un AU texte supporte le pseudo-élément 'first-letter' (ils ne le feront probablement pas), l'exemple pourrait être affiché comme suit :
| ES PREMIERS |__ mots d'un article dans Le Monde.
La séquence de balise fictionnelle est :
<p> <span> <p:first-letter> L </p:first-letter>ES PREMIERS </span> mots d'un article dans Le Monde. </p>
Notez que le pseudo-élément 'first-letter' est contigue au contenu (i.e. la caractère initial), alors que la balise de départ du pseudo-élément 'first-line' est insérée juste la balise de l'élément duquel il dépend.
L'AU défini quels caractères sont à l'intérieur de l'élément 'first-letter'. Normallement, les guillemets qui précèdent la première lettre devraient être inclus :
|| /\ mour d'un / \ soir ne /----\ lui laissa / \ qu'un sombre espoir", dit le poête.
Lorsque le paragraphe démarre avec une autre ponctuation (e.g. parenthèse et points de suspension) ou d'autres caractères qui ne sont pas normalement considérés comme des lettres (e.g. chiffres et symboles mathématiques), le pseudo-élément 'first-letter' est habituellement ignoré.
Certaines langues ont des règles particulières sur la façon de traiter les combinaisons de lettre. En hollandais, par exemple, si la combinaison "ij" apparaît au début d'un mot, les deux lettres doivent être alors considérées comme faisant d'une seule et même lettre à l'intérieur du pseudo-élément 'first-letter'.
Le pseudo-élément 'first-letter' peut être seulement lié à un élément de type bloc.
Dans un sélecteur contextuel, les pseudo-éléments sont autorisés uniquement à la fin du sélecteur :
BODY P:first-letter { color: purple }
Les pseudo-éléments peuvent être combinés avec des classes dans les sélecteurs :
P.initial:first-letter { color: red } <p class="initial">Premier paragraphe</p>
L'exemple précédent devrait transformer la première lettre de tous les éléments P avec 'CLASS="initial"' en rouge. Lorsque ceci est combiné avec des classes ou des pseudo-classes, les pseudo-éléments doivent être spécifiés à al fin du sélecteur. Uniquement un pseudo-élément peut être spécifié par sélecteur.
Plusieurs pseudo éléments peuvent être combinés :
P { color: red; font-size: 12pt } P:first-letter { color: green; font-size: 200% } P:first-line { color: blue } <p>Un texte qui se termine en deux lignes</p>
Dans cet exemple, la première lettre de chaque élément 'P' devrait être verte avec une taille de police de 24pt. Le reste de la première ligne (tel qu'affiché sur le canvas) sera bleu alors que le reste du paragraphe sera rouge. Si l'on considère qu'une fin de ligne surviendra avant le mot "termine", la séquence fictive est :
<P> <P:first-line> <P:first-letter> U </P:first-letter>n texte qui se </P:first-line> termine en deux lignes </P>
Notez que l'élément 'first-letter' est à l'intérieur de l'élément 'first-line'. Les propriétés paramétrées pour 'first-line' seront héritées par 'first-letter', mais sont remplacées si les mêmes propriétés sont paramétrées pour 'first-letter'.
Si un pseudo élément sépare un véritable élément, les balises supplémentaires nécessaires doivent être regénérées dans la séquence de balise fictive. Par exemple, si un élément SPAN s'étend sur une balise </P:first-line>, un ensemble de balises ouvrante et fermante doivent être regénérées et la séquence fictive précédente devient :
<P> <P:first-line> <SPAN> Ce texte est à l'intérieur d'un long </SPAN> </P:first-line> <SPAN> élément span </SPAN>
En CSS, plus d'une feuille de style peut influencer la présentation simultanément. Il y a deux raisons à ceci : modularité et équilibre des priorités auteur/lecteur.
@import url(http://www.style.org/pastoral); @import url(http://www.style.org/marine); H1 { color: red } /* surpasse les feuilles de style importées */
Parfois des conflits peuvent avoir lieu entre les feuilles de style qui influencent la présentation. La résolution des conflits est basée sur la pondération de chaque règle de style. Par défaut, le poids des règles du lecteur est plus faible que le poids des règles de l'auteur du document. I.e., s'il existe des conflites entre les feuilles de style d'un document téléchargé et les feuilles de style personnelles du lecteur, les règles de l'auteur seront utilisées. Les règles du lecteur ainsi que les règles de l'auteur ont un poids supérieur aux valeurs par défaut de l'AU.
Les feuilles de style importées cascadent également entre elles, dans l'ordre dans lequel elles sont importées, en respectant les règles de cascade définies plus bas. Toutes les règles spécifiées dans la feuille de style elle-même surpassent les règles des feuilles de style importées. C'est à dire, les feuilles de style importées ont un poids moins important dans l'ordre de la cascade que les règles de la feuille de style proprement dit. Les feuilles de style peuvent elles-mêmes importer ou surpasser d'autres feuilles de style, récursivement.
Dans CSS1, toutes les déclarations '@import' doivent avoir lieu au début de la feuille de style, avant toutes autres déclarations. Cela permet de voir plus facilement quelles sont les règles de la feuille de style elle-même qui surpassent les règles des feuilles de style importées.
Les concepteurs de feuilles de style peuvent augmenter le poids de leurs déclarations CSS :
H1 { color: black ! important; background: white ! important } P { font-size: 12pt ! important; font-style: italic }
Dans l'exemple précédent, les trois premières déclarations ont augmenté le poids, alors que la dernière déclaration a un poids normal.
Une règle de lecteur avec une déclaration importante surpassera une règle d'auteur avec une déclaration normale. Une règle d'auteur avec une déclaration importante surpassera une règle de lecteur avec une déclaration importante.
Les règles de conflits sont intrinsèques au mécanisme CSS. Pour trouver la valeur d'une combinaison élément/propriété, l'algorithme suivant doit être respecté :
LI {...} /* a=0 b=0 c=1 -> specificité = 1 */ UL LI {...} /* a=0 b=0 c=2 -> specificité = 2 */ UL OL LI {...} /* a=0 b=0 c=3 -> specificité = 3 */ LI.red {...} /* a=0 b=1 c=1 -> specificité = 11 */ UL OL LI.red {...} /* a=0 b=1 c=3 -> specificité = 13 */ #x34y {...} /* a=1 b=0 c=0 -> specificité = 100 */
Les pseudo-éléments et les pseudo-classes sont comptés respectivement comme des éléments et des classes normaux.
La recherche de la valeur de la propriété peut être arrêtée lorsqu'une règle a un plus haut poids que les autres règles qui s'appliquent à la même combinaison élément/propriété.
Cette stratégie donne aux feuilles de style de l'auteur un poids bien plus important que celui du lecteur. Il est bien sûr important que le lecteur ait la possibilité de désactiver l'influence de certaines feuilles de styles, e.g. grâce à un menu déroulant.
Une déclaration dans l'attribut 'STYLE' d'un élément (voir section 1.1 pour avoir un exemple) a le même poids qu'une déclaration avec un sélecteur basé sur l'ID qui est spécifié à la fin de la feuille de style :
<style type="text/css"> #x97z { color: blue } </style> <P id="x97z" style="color: red">
Dans l'exemple précédent, la couleur de l'élément 'P' devrait être rouge. Bien que la spécificité est la même pour les deux déclarations, la déclaration dans l'attribut 'STYLE' surpassera celle dans l'élément 'STYLE' à cause de la règle de cascade numéro 5.
L'AU peut choisir de définir d'autres attributs HTML stylistiques, par exemple 'ALIGN'. Si tel était le cas, ces attributs sont traduits dans les règles CSS correspondantes avec une spécificité égale à 1. Les règles sont supposées être au début de la feuille de style auteur et peuvent être surpassée par les règles des feuilles de style suivantes. Dans la phase de transition, cette règle facilitera la coexistence des attributs stylistiques et des feuilles de style.
CSS1 considère un modèle de formatage basé sur une simple boîte où chaque élément formaté correspond à une ou plusieurs boites rectangulaires. (Les éléments qui ont une valeur 'display' égale à 'none' ne sont pas formattés et ne seront donc pas définis en tant que boîte.) Toutes les boîtes ont une aire de contenu centrale avec des marges intérieures l'entourant, des bordures, et des marges.
_______________________________________ | | | marge (transparente) | | _________________________________ | | | | | | | bordure | | | | ___________________________ | | | | | | | | | | | marge intérieure | | | | | | _____________________ | | | | | | | | | | | | | | | contenu | | | | | | | |_____________________| | | | | | |___________________________| | | | |_________________________________| | |_______________________________________| | largeur élément | | largeur boîte |
Les taille de la marge, de la bordure et de la marge intérieure sont définies respectivement par les propriétés margin (5.5.1-5.5.5), padding (5.5.6-5.5.10), et border (5.5.11-5.5.22). L'aire de marge intérieure utilise le même fond que l'élément lui-même (défini par les propriétés background (5.3.2-5.3.7)). La couleur et le style pour la bordure sont définis par les propriétés border. Les marges sont toujours transparentes, donc la couleur visible sera celle de l'élément parent.
La taille de la boîte est la somme de la largeur de l'élément (i.e. texte formaté ou image) et des aires de la marge intérieure, de la bordure et de la marge.
Du point de vue du formateur, il y a deux types principaux d'éléments : bloc ou flot de texte (inline).
Les éléments avec une valeur 'display' de 'block' ou de 'list-item' sont des éléments de type bloc. Egalement, les éléments flottants (éléments avec une valeur 'float' autre que 'none') sont des éléments de type bloc.
L'exemple suivant montre comment les marges et les marges intérieures formatent un élément 'UL' avec deux enfants. Pour simplier le diagramme, il n'y a pas de bordures. Les marqueurs lettres dans cet exemple ne sont pas corrects syntaxiquement en CSS1, mais sont un moyen pratique de pointer les valeurs sur la figure.
<STYLE TYPE="text/css"> UL { background: red; margin: A B C D; padding: E F G H; } LI { color: white; background: blue; /* le texte est blanc sur fond bleu */ margin: a b c d; padding: e f g h; } </STYLE> .. <ul> <li>1er élément de la liste</li> <li>2nd élément de la liste</li> </ul>
_______________________________________________________ | | | A UL marge (transparente) | | _______________________________________________ | | D | | B | | | E UL marge intérieure (rouge) | | | | _______________________________________ | | | | H | | F | | | | | a LI marge (transparente, | | | | | | donc on voit le rouge) | | | | | | _______________________________ | | | | | | d | | b | | | | | | | e LI marge intér. (bleu) | | | | | | | | | | | | | | | | h 1er élément de la liste f | | | | | | | | | | | | | | | | g | | | | | | | |_______________________________| | | | | | | | | | | | | max(a, c) | | | <- note le max | | | _______________________________ | | | | | | | | | | | | | | d | e LI marge intér. (bleu)| | | | | | | | | | | | | | | | h 2nd élément de la liste f | | | | | | | | | | | | | | | | g | | | | | | | |_______________________________| | | | | | | | | | | | | c LI marge (transparente, | | | | | | donc on voit le rouge) | | | | | |_______________________________________| | | | | | | | | G | | | |_______________________________________________| | | | | C | |_______________________________________________________|
Techniquement, les propriétés padding et margin ne sont pas héritées. Mais, comme l'exemple le montre, le placement d'un élément est relatif à ces ancêtres ou à ses frêres, donc les propriétés padding et margin ont un effet sur leurs enfants.
S'il y avait eu des bordures dans l'exemple précédent, elles auraient été visibles entre les marges intérieures et les marges.
Le diagramme suivant introduit une terminologie utile :
--------------- <-- haut marge haute --------------- bordure haute --------------- marge intérieure haute +-------------+ <-- haut intérieur | | | | | | | | | marge | bordure | mar. int.| | mar. int.| bordure | marge | |--gauche--|--gauche--|--gauche--|-- contenu --|--droite--|--droite--|--droite--| | | | | | | | | +-------------+ <-- bas intérieur ^ ^ ^ ^ côté côté gauche intérieur côté droit intérieur côté gauche droit extérieur marge intérieure bas extérieur --------------- bordure bas --------------- marge bas --------------- <-- bas
Le côté gauche extérieur est le côté d'un élément en prenant en compte sa marge intérieur, sa bordure et sa marge. Le côté gauche intérieur est le côté du contenu uniquement, en dehors de toute marge intérieure, bordure ou marge. De même pour la droite. Le haut (top) est le haut de l'élément y compris toute marge intérieure, bordure et marge ; ceci est uniquement défini pour les éléments flot de texte ou flottant, non pour les éléments de type bloc non flottant. Le haut intérieur est le haut du contenu en dehors de toute marge intérieure, bordure ou marge. Le bas (bottom) est le bas de l'élément, y compris toute marge intérieure, bordure, et marge ; il est uniquement défini pour les éléments flot de texte et flottant, et pas pour les éléments de type bloc non flottant. Le bas intérieur est le bas de l'élément en dehors de toute marge intérieure, bordure et marge.
La largeur (width) d'un élément est la largeure du contenu, i.e., la distance entre le côté intérieur gauche et le côté intérieur droit. La hauteur (height) est la hauteur du contenu, i.e., la distance du haut intérieur au bas intérieur.
La largeur de la marge sur les éléments de type bloc non flottants est la distance minimum des côtés des boites qui l'entourent. Deux marges verticales adjacentes ou plus (i.e., sans bordure, marge intérieure ou contenu entre elles) sont fusionner de façon à utiliser le maximum des valeurs de marge. Dans la plupart des cas, après fusionner les marges verticales, le résultat est visuellement plus agréable et plus proche de ce que le concepteur attend. Dans l'exemple précédent, les marges entre les deux éléments 'LI' sont fusionnées en utilisant le maximum de 'margin-bottom' du premier élément 'LI' et le maximum de 'margin-top' du second élément 'LI'. De la même manière, si la marge intérieure entre l'élément 'UL' et le premier 'LI' (le marqueur "E") avait été nulle, les marges des éléments UL et des premiers éléments LI auraient été fusionnés.
Dans le cas de marges à valeur négative, la valeur absolue maximum des marges adjacentes négatives est déduite de la valeur maximum des marges adjacentes positives. Si il n'y a pas de marges positives, le maximum absolu des marges adjacentes négatives est déduit à partir de zéro. @@@Pas clair, demander à Bert@@@
La position horizontale et la taille d'un élément de type bloc non flottant est déterminé par sept propriétés : 'margin-left', 'border-left', 'padding-left', 'width', 'padding-right', 'border-right' et 'margin-right'. La somme de ces septs éléments est toujours égale à la valeur 'width' (largeur) de l'élément parent.
Par défaut, la valeur 'width' d'un élément est 'auto'. Si l'élément n'est pas un élémént remplacé, cela signifie que la valeur 'width' est calculé par l'AU, et donc que la somme des sept propriétés mentionnées ci-dessus est égale à la largeur du parent. Si l'élément est un élément remplacé, la valeur 'auto' de 'width' est automatiquement remplacée par la largeur intrinsèque de l'élément.
Trois des septs propriétés peuvent être paramétrées avec la valeur 'auto' : 'margin-left', 'width' et 'margin-right'. Pour les éléments remplacés, une valeur 'auto' pour 'width' est remplacé par la largeur intrinsèque, pour ceux-ci, il n'y a donc que deux valeurs 'auto' possibles.
Le 'width' possède une valeur minimum non-négative définie par l'AU (qui peut varier d'un élément à l'autre et souvent dépend des autres propriétés). Si 'width' va en dessous de cette limite, que ceci ait été explicitement indiqué, ou parce-que c'était 'auto' et que les règles suivantes le rendront trop petit, la valeur sera remplacée par la valeur minimum.
Si une et un seule des propriétés 'margin-left', 'width' ou 'margin-right' est 'auto', l'AU donnera à cette propriété une valeur qui sera la somme des sept valeurs égales à la largeur de l'élément parent.
Si aucune de ces propriétés sont de valeur 'auto', 'margin-right' prendra la valeur 'auto'.
Si plus d'une des trois propriétés a pour valeur 'auto', et l'une d'entre-elles est 'width', alors les autres ('margin-left' et/ou 'margin-right') prendront la valeur zéro et 'width' prendra la valeur requise pour que la somme des 7 valeurs égale la largeur de l'élément parent.
Enfin, si 'margin-left' ainsi que 'margin-right' ont pour valeur 'auto', elles prendront des valeurs égales. Cela aura pour effet de centrer l'élément à l'intérieur de son élément parent.
Si l'une des sept propriétés prend la valeur 'auto' dans un élément qui est flot de texte ou flottant, la propriété sera traitée comme ayant une valeur nulle.
Contrairement aux marges verticales, les marges horizontales ne sont pas fusionnées.
Les éléments avec une valeur de propriété 'display' égale à 'list-item' sont formatés comme des éléments de type bloc, mais précédé par un marqueur de liste (une puce). Le type de marqueur est déterminé par la propriété 'list-style'. Le marqueur est placé en fonction de la valeur de la propriété 'list-style' :
<STYLE TYPE="text/css"> UL { list-style: outside } UL.compact { list-style: inside } </STYLE> <UL> <LI>le premier élément de la liste vient en premier</LI> <LI>le second élément de la liste vient en second</LI> </UL> <UL CLASS="COMPACT"> <LI>le premier élément de la liste vient en premier</LI> <LI>le second élément de la liste vient en second</LI> </UL>
L'exemple précédent peut être formaté comme suit :
* le premier élément de la liste
vient en premier
* le second élément de la liste
vient en second
* le premier élement de la liste
vient en premier
* le second élément de la liste
vient en second
Dans les textes orientés de droite à gauche, les marqueurs devraient être sur le côté droit de la boîte.
En utilisant la propriété 'float', un élément peut être déclaré être à l'extérieur du flot normal des éléments et alors être formatté comme un élément de type bloc. Par exemple, en donnant à la propriété 'float' d'une image, la valeur 'left', l'image est déplacée sur la gauche jusqu'au point de contact avec la marge, la marge intérieure ou la bordure d'un autre élément de type bloc. Le flot normal enrobera le côté droit. Les marges, bordures et marges intérieures de l'élément en lui-même seront respectés, et les marges ne seront jamais fusionnées avec les marges adjacentes.
Un élément flottant est placé en fonction des contraintes suivantes (voir section 4.1 pour une explication des termes) :
<STYLE TYPE="text/css"> IMG { float: left } BODY, P, IMG { margin: 2em } </STYLE> <BODY> <P> <IMG SRC=img.gif> Some sample text that has no other... </BODY>
The above example could be formatted as:
________________________________________ | | max(BODY margin, P margin) | ______________________________ | | | Some sample text | B | P | IMG margins that has no other | O | | _____ purpose than to | D | m | | | show how floating | Y | a | | IMG | elements are moved | | r | | | to the side of the | m | g | |_____| parent element | a | i | while honoring | r | n | margins, borders | g | | and padding. Note | i | |how adjacent vertical margins | n | |are collapsed between non- | | |floating block-level elements.
Note that the margin of the 'P' element encloses the floating 'IMG' element.
There are two situations when floating elements can overlap with the margin, border and padding areas of other elements:
Elements that are not formatted as block-level elements are inline elements. An inline element can share line space with other elements. Consider this example:
<P>Several <EM>emphasized</EM> words <STRONG>appear</STRONG>.</P>
The 'P' element is normally block-level, while 'EM' and 'STRONG' are inline elements. If the 'P' element is wide enough to format the whole element on one line, there will be two inline elements on the line:
Several emphasized words appear.
If there is not enough room on one line an inline element will be split into several boxes:
<P>Several <EM>emphasized words</EM> appear here.</P>
The above example may be formatted as:
Several emphasized words appear here.
If the inline element has margins, borders, padding or text decorations attached, these will have no effect where the element is broken:
---------- Several |emphasized ---------- ----- words| appear here. -----
(The "figure" above is slightly distorted due to the use of ASCII graphics. See section 4.4 for a description of how to calculate the height of lines.
A replaced element is an element which is replaced by content pointed to from the element. E.g., in HTML, the 'IMG' element is replaced by the image pointed to by the 'SRC' attribute. One can assume that replaced elements come with their own intrinsic dimensions. If the value of the 'width' property is 'auto', the intrinsic width is used as the width of the element. If a value other than 'auto' is specified in the style sheet, this value is used and the replaced element is resized accordingly (the resize method will depend on the media type). The 'height' property is used in the same manner.
Replaced elements can be either block-level or inline.
All elements have a 'line-height' property that, in principle, gives the total height of a line of text. Space is added above and below the text of the line to arrive at that line height. For example, if the text is 12pt high and 'line-height' is set to '14pt', an extra space of 2pt is added, namely 1pt above and 1pt below the line. Empty elements influence these calculations just like elements with content.
The difference between the font size and the 'line-height' is called the leading. Half the leading is called the half-leading. After formatting, each line will form a rectangular line-box.
If a line of text contains sections with different 'line-height' values (because there are inline elements on the line), then each of those sections has its own half-leading above and below. The height of the line-box is from the top of the highest section to the bottom of the lowest one. Note that the top and bottom do not necessarily correspond to the tallest element, since elements can be positioned vertically with the 'vertical-align' property. To form a paragraph, each line-box is stacked immediately below the previous line.
Note that any padding, border or margin above and below non-replaced inline elements does not influence the height of the line. In other words: if the 'line-height' is too small for the chosen padding or border, it will overlap with text on other lines.
Replaced elements (e.g. images) on the line can make the line-box bigger, if the top of the replaced element (i.e., including all of its padding, border and margin) is above the tallest text section, or if the bottom is below the lowest.
In the normal case, when there is only one value of 'line-height' throughout a paragraph, and no tall images, the definition above will ensure that baselines of successive lines are exactly 'line-height' apart. This is important when columns of text in different fonts have to be aligned, for example in a table.
Note that this doesn't preclude the text on two adjacent lines from overlapping each other. The 'line-height' may be smaller than the height of the text, in which case the leading will be negative. This is useful if you know that the text will contain no descenders (e.g., because it only contains uppercase), so the lines can be put closer together.
The canvas is the part of the UA's drawing surface onto which documents are rendered. No structural element of a document corresponds to the canvas, and this raises two issues when formatting a document:
A reasonable answer to the first question is that the initial width of the canvas is based on the window size, but CSS1 leaves this issue for the UA to decide. It is also reasonable to expect the UA to change the width of the canvas when the window is resized, but this is also outside the scope of CSS1.
HTML extensions have set a precedent for the second question: attributes on the 'BODY' element set the background of the whole canvas. To support designers' expectations, CSS1 introduces a special rule to find the canvas background:
If the 'background' value of the 'HTML' element is different from 'transparent' then use it, else use the 'background' value of the 'BODY' element. If the resulting value is 'transparent', the rendering is undefined.
This rule allows:
<HTML STYLE="background: url(http://style.com/marble.png)"> <BODY STYLE="background: red">
In the example above, the canvas will be covered with "marble". The background of the 'BODY' element (which may or may not fully cover the canvas) will be red.
Until other means of addressing the canvas become available, it is recommended that canvas properties are set on the 'BODY' element.
The current CSS1 properties and values cannot describe the behavior of the 'BR' element. In HTML, the 'BR' element specifies a line break between words. In effect, the element is replaced by a line break. Future versions of CSS may handle added and replaced content, but CSS1-based formatters must treat 'BR' specially.
Style sheets influence the presentation of documents by assigning values to style properties. This section lists the defined style properties, and their corresponding list of possible values, of CSS1.
In the text below, the allowed values for each property are listed with a syntax like the following:
Value: N | NW | NE
Value: [ <length> | thick | thin ]{1,4}
Value: [<family-name> , ]* <family-name>
Value: <url>? <color> [ / <color> ]?
Value: <url> || <color>
The words between "<" and ">" give a type of value. The most common types are <length>, <percentage>, <url>, <number> and <color>; these are described in section 6. The more specialized types (e.g. <font-family> and <border-style>) are described under the corresponding property.
Other words are keywords that must appear literally, without quotes. The slash (/) and the comma (,) must also appear literally.
Several things juxtaposed mean that all of them must occur, in the given order. A bar (|) separates alternatives: one of them must occur. A double bar (A || B) means that either A or B or both must occur, in any order. Brackets ([]) are for grouping. Juxtaposition is stronger than the double bar, and the double bar is stronger than the bar. Thus "a b | c || d e" is equivalent to "[ a b ] | [ c || [ d e ]]".
Every type, keyword, or bracketed group may be followed by one of the following modifiers:
Setting font properties will be among the most common uses of style sheets. Unfortunately, there exists no well-defined and universally accepted taxonomy for classifying fonts, and terms that apply to one font family may not be appropriate for others. E.g. 'italic' is commonly used to label slanted text, but slanted text may also be labeled as being Oblique, Slanted, Incline, Cursive or Kursiv. Therefore it is not a simple problem to map typical font selection properties to a specific font.
CSS1 defines the properties 'font-family', 'font-style', 'font-variant' and 'font-weight', 'font-size', 'font'.
Because there is no accepted, universal taxonomy of font properties, matching of properties to font faces must be done carefully. The properties are matched in a well-defined order to insure that the results of this matching process are as consistent as possible across UAs (assuming that the same library of font faces is presented to each of them).
(The above algorithm can be optimized to avoid having to revisit the CSS1 properties for each character.)
The per-property matching rules from (2) above are as follows:
Value: [[<family-name> | <generic-family>],]*
[<family-name> | <generic-family>]
Initial: UA specific
Applies to: all elements
Inherited: yes
Percentage values: N/A
The value is a prioritized list of font family names and/or generic family names. Unlike most other CSS1 properties, values are separated by a comma to indicate that they are alternatives:
BODY { font-family: gill, helvetica, sans-serif }
There are two types of list values:
Style sheet designers are encouraged to offer a generic font family as a last alternative.
Font names containing whitespace should be quoted:
BODY { font-family: "new century schoolbook", serif } <BODY STYLE="font-family: 'My own font', fantasy">
If quoting is omitted, any whitespace characters before and after the font name are ignored and any sequence of whitespace characters inside the font name is converted to a single space.
Value: normal | italic | oblique
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
The 'font-style' property selects between normal (sometimes referred to as "roman" or "upright"), italic and oblique faces within a font family.
A value of 'normal' selects a font that is classified as 'normal' in the UA's font database, while 'oblique' selects a font that is labeled 'oblique'. A value of 'italic' selects a font that is labeled 'italic', or, if that is not available, one labeled 'oblique'.
The font that is labeled 'oblique' in the UA's font database may actually have been generated by electronically slanting a normal font.
Fonts with Oblique, Slanted or Incline in their names will typically be labeled 'oblique' in the UA's font database. Fonts with Italic, Cursive or Kursiv in their names will typically be labeled 'italic'.
H1, H2, H3 { font-style: italic } H1 EM { font-style: normal }
In the example above, emphasized text within 'H1' will appear in a normal face.
Value: normal | small-caps
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
Another type of variation within a font family is the small-caps. In a small-caps font the lower case letters look similar to the uppercase ones, but in a smaller size and with slightly different proportions. The 'font-variant' property selects that font.
A value of 'normal' selects a font that is not a small-caps font, 'small-caps' selects a small-caps font. It is acceptable (but not required) in CSS1 if the small-caps font is a created by taking a normal font and replacing the lower case letters by scaled uppercase characters. As a last resort, uppercase letters will be used as replacement for a small-caps font.
The following example results in an 'H3' element in small-caps, with emphasized words in oblique small-caps:
H3 { font-variant: small-caps } EM { font-style: oblique }
There may be other variants in the font family as well, such as fonts with old-style numerals, small-caps numerals, condensed or expanded letters, etc. CSS1 has no properties that select those.
CSS1 core: insofar as this property causes text to be transformed to uppercase, the same considerations as for 'text-transform' apply.
Value: normal | bold | bolder | lighter | 100 | 200 | 300 | 400
| 500 | 600 | 700 | 800 | 900
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
The 'font-weight' property selects the weight of the font. The values '100' to '900' form an ordered sequence, where each number indicates a weight that is at least as dark as its predecessor. The keyword 'normal' is synonymous with '400', and 'bold' is synonymous with '700'. Keywords other than 'normal' and 'bold' have been shown to be often confused with font names and a numerical scale was therefore chosen for the 9-value list.
P { font-weight: normal } /* 400 */ H1 { font-weight: 700 } /* bold */
The 'bolder' and 'lighter' values select font weights that are relative to the weight inherited from the parent:
STRONG { font-weight: bolder }
Child elements inherit the resultant weight, not the keyword value.
Fonts (the font data) typically have one or more properties whose values are names that are descriptive of the "weight" of a font. There is no accepted, universal meaning to these weight names. Their primary role is to distinguish faces of differing darkness within a single font family. Usage across font families is quite variant; for example a font that you might think of as being bold might be described as being Regular, Roman, Book, Medium, Semi- or DemiBold, Bold, or Black, depending on how black the "normal" face of the font is within the design. Because there is no standard usage of names, the weight property values in CSS1 are given on a numerical scale in which the value '400' (or 'normal') corresponds to the "normal" text face for that family. The weight name associated with that face will typically be Book, Regular, Roman, Normal or sometimes Medium.
The association of other weights within a family to the numerical weight values is intended only to preserve the ordering of darkness within that family. However, the following heuristics tell how the assignment is done in typical cases:
The following two examples illustrate the process. Assume four weights in the "Example1" family, from lightest to darkest: Regular, Medium, Bold, Heavy. And assume six weights in the "Example2" family: Book, Medium, Bold, Heavy, Black, ExtraBlack. Note how in the second example it has been decided not to assign "Example2 ExtraBlack" to anything.
Available faces | Assignments | Filling the holes ----------------------+---------------+------------------- "Example1 Regular" | 400 | 100, 200, 300 "Example1 Medium" | 500 | "Example1 Bold" | 700 | 600 "Example1 Heavy" | 800 | 900
Available faces | Assignments | Filling the holes ----------------------+---------------+------------------- "Example2 Book" | 400 | 100, 200, 300 "Example2 Medium" | 500 | "Example2 Bold" | 700 | 600 "Example2 Heavy" | 800 | "Example2 Black" | 900 | "Example2 ExtraBlack" | (none) |
Since the intent of the relative keywords 'bolder' and 'lighter' is to darken or lighten the face within the family and because a family may not have faces aligned with all the symbolic weight values, the matching of 'bolder' is to the next darker face available on the client within the family and the matching of 'lighter' is to the next lighter face within the family. To be precise, the meaning of the relative keywords 'bolder' and 'lighter' is as follows:
There is no guarantee that there will be a darker face for each of the 'font-weight' values; for example, some fonts may have only a normal and a bold face, others may have eight different face weights. There is no guarantee on how a UA will map font faces within a family to weight values. The only guarantee is that a face of a given value will be no less dark than the faces of lighter values.
Value: <absolute-size> | <relative-size> |
<length> | <percentage>
Initial: medium
Applies to: all elements
Inherited: yes
Percentage values: relative to parent element's font size
Length and percentage values should not take the font size table into account when calculating the font size of the element.
Negative values are not allowed.
On all other properties, 'em' and 'ex' length values refer to the font size of the current element. On the 'font-size' property, these length units refer to the font size of the parent element.
Note that an application may reinterpret an explicit size, depending on the context. E.g., inside a VR scene a font may get a different size because of perspective distortion.
Examples:
P { font-size: 12pt; } BLOCKQUOTE { font-size: larger } EM { font-size: 150% } EM { font-size: 1.5em }
If the suggested scaling factor of 1.5 is used, the last three declarations are identical.
Value: [ <font-style> || <font-variant> ||
<font-weight> ]? <font-size> [ / <line-height> ]?
<font-family>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: yes
Percentage values: allowed on <font-size> and
<line-height>
The 'font' property is a shorthand property for setting 'font-style' 'font-variant' 'font-weight' 'font-size', 'line-height' and 'font-family' at the same place in the style sheet. The syntax of this property is based on a traditional typographical shorthand notation to set multiple properties related to fonts.
For a definition of allowed and initial values, see the previously defined properties. Properties for which no values are given are set to their initial value.
P { font: 12pt/14pt sans-serif } P { font: 80% sans-serif } P { font: x-large/110% "new century schoolbook", serif } P { font: bold italic large Palatino, serif } P { font: normal small-caps 120%/120% fantasy }
In the second rule, the font size percentage value ('80%') refers to the font size of the parent element. In the third rule, the line height percentage refers to the font size of the element itself.
In the first three rules above, the 'font-style', 'font-variant' and 'font-weight' are not explicitly mentioned, which means they are all three set to their initial value ('normal'). The fourth rule sets the 'font-weight' to 'bold', the 'font-style' to 'italic' and implicitly sets 'font-variant' to 'normal'.
The fifth rule sets the 'font-variant' ('small-caps'), the 'font-size' (120% of the parent's font), the 'line-height' (120% times the font size) and the 'font-family' ('fantasy'). It follows that the keyword 'normal' applies to the two remaining properties: 'font-style' and 'font-weight'.
These properties describe the color (often called foreground color) and background of an element (i.e. the surface onto which the content is rendered). One can set a background color and/or a background image. The position of the image, if/how it is repeated, and whether it is fixed or scrolled relative to the canvas can also be set.
The 'color' property inherits normally. The background properties do not inherit, but the parent element's background will shine through by default because of the initial 'transparent' value on 'background-color'.
Value: <color>
Initial: UA specific
Applies to: all elements
Inherited: yes
Percentage values: N/A
This property describes the text color of an element (often referred to as the foreground color). There are different ways to specify red:
EM { color: red } /* natural language */ EM { color: rgb(255,0,0) } /* RGB range 0-255 */
See section 6.3 for a description of possible color values.
Value: <color> | transparent
Initial: transparent
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the background color of an element.
H1 { background-color: #F00 }
Value: <url> | none
Initial: none
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.
BODY { background-image: url(marble.gif) } P { background-image: none }
Value: repeat | repeat-x | repeat-y | no-repeat
Initial: repeat
Applies to: all elements
Inherited: no
Percentage values: N/A
If a background image is specified, the value of 'background-repeat' determines how/if the image is repeated.
A value of 'repeat' means that the image is repeated both horizontally and vertically. The 'repeat-x' ('repeat-y') value makes the image repeat horizontally (vertically), to create a single band of images from one side to the other. With a value of 'no-repeat', the image is not repeated.
BODY { background: red url(pendant.gif); background-repeat: repeat-y; }
In the example above, the image will only be repeated vertically.
Value: scroll | fixed
Initial: scroll
Applies to: all elements
Inherited: no
Percentage values: N/A
If a background image is specified, the value of 'background-attachment' determines if it is fixed with regard to the canvas or if it scrolls along with the content.
BODY { background: red url(pendant.gif); background-repeat: repeat-y; background-attachment: fixed; }
CSS1 core: UAs may treat 'fixed' as 'scroll'. However, it is recommended they interpret 'fixed' correctly, at least on the HTML and BODY elements, since there is no way for an author to provide an image only for those browsers that support 'fixed'. (See section 7.)
Value: [<percentage> | <length>]{1,2} | [top | center
| bottom] || [left | center | right]
Initial: 0% 0%
Applies to: block-level and replaced elements
Inherited: no
Percentage values: refer to the size of the element itself
If a background image has been specified, the value of 'background-position' specifies its initial position.
With a value pair of '0% 0%', the upper left corner of the image is placed in the upper left corner of the box that surrounds the content of the element (i.e., not the box that surrounds the padding, border or margin). A value pair of '100% 100%' places the lower right corner of the image in the lower right corner of the element. With a value pair of '14% 84%', the point 14% across and 84% down the image is to be placed at the point 14% across and 84% down the element.
With a value pair of '2cm 2cm', the upper left corner of the image is placed 2cm to the right and 2cm below the upper left corner of the element.
If only one percentage or length value is given, it sets the horizontal position only, the vertical position will be 50%. If two values are given, the horizontal position comes first. Combinations of length and percentage values are allowed, e.g. '50% 2cm'. Negative positions are allowed.
One can also use keyword values to indicate the position of the background image. Keywords cannot be combined with percentage values, or length values. The possible combinations of keywords and their interpretations are as follows:
Examples:
BODY { background: url(banner.jpeg) right top } /* 100% 0% */ BODY { background: url(banner.jpeg) top center } /* 50% 0% */ BODY { background: url(banner.jpeg) center } /* 50% 50% */ BODY { background: url(banner.jpeg) bottom } /* 50% 100% */
If the background image is fixed with regard to the canvas (see the 'background-attachment' property above), the image is placed relative to the canvas instead of the element. E.g.:
BODY { background-image: url(logo.png); background-attachment: fixed; background-position: 100% 100%; }
In the example above, the image is placed in the lower right corner of the canvas.
Value: <background-color> || <background-image> ||
<background-repeat> || <background-attachment> ||
<background-position>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: allowed on <background-position>
The 'background' property is a shorthand property for setting the individual background properties (i.e., 'background-color', 'background-image', 'background-repeat', 'background-attachment' and 'background-position') at the same place in the style sheet.
Possible values on the 'background' properties are the set of all possible values on the individual properties.
BODY { background: red } P { background: url(chess.png) gray 50% repeat fixed }
The 'background' property always sets all the individual background properties. In the first rule of the above example, only a value for 'background-color' has been given and the other individual properties are set to their initial value. In the second rule, all individual properties have been specified.
Value: normal | <length>
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
The length unit indicates an addition to the default space between words. Values can be negative, but there may be implementation-specific limits. The UA is free to select the exact spacing algorithm. The word spacing may also be influenced by justification (which is a value of the 'text-align' property).
H1 { word-spacing: 1em }
Here, the word-spacing between each word in 'H1' elements would be increased by '1em'.
CSS1 core: UAs may interpret any value of 'word-spacing' as 'normal'. (See section 7.)
Value: normal | <length>
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: N/A
The length unit indicates an addition to the default space between characters. Values can be negative, but there may be implementation-specific limits. The UA is free to select the exact spacing algorithm. The letter spacing may also be influenced by justification (which is a value of the 'align' property).
BLOCKQUOTE { letter-spacing: 0.1em }
Here, the letter-spacing between each character in 'BLOCKQUOTE' elements would be increased by '0.1em'.
With a value of 'normal', the UAs may change the space between letters to justify text. This will not happen if 'letter-spacing' is explicitly set to a <length> value:
BLOCKQUOTE { letter-spacing: 0 } BLOCKQUOTE { letter-spacing: 0cm }
When the resultant space between two letters is not the same as the default space, UAs should not use ligatures.
CSS1 core: UAs may interpret any value of 'letter-spacing' as 'normal'. (See section 7.)
Value: none | [ underline || overline || line-through || blink ]
Initial: none
Applies to: all elements
Inherited: no, but see clarification below
Percentage values: N/A
This property describes decorations that are added to the text of an element. If the element has no text (e.g. the 'IMG' element in HTML) or is an empty element (e.g. '<EM></EM>'), this property has no effect. A value of 'blink' causes the text to blink.
The color(s) required for the text decoration should be derived from the 'color' property value.
This property is not inherited, but elements should match their parent. E.g., if an element is underlined, the line should span the child elements. The color of the underlining will remain the same even if descendant elements have different 'color' values.
A:link, A:visited, A:active { text-decoration: underline }
The example above would underline the text of all links (i.e., all 'A' elements with a 'HREF' attribute).
UAs must recognize the keyword 'blink', but are not required to support the blink effect.
Value: baseline | sub | super | top | text-top | middle | bottom
| text-bottom | <percentage>
Initial: baseline
Applies to: inline elements
Inherited: no
Percentage values: refer to the 'line-height' of the element
itself
The property affects the vertical positioning of the element. One set of keywords is relative to the parent element:
Another set of properties are relative to the formatted line that the element is a part of:
Using the 'top' and 'bottom' alignment, unsolvable situations can occur where element dependencies form a loop.
Percentage values refer to the value of the 'line-height' property of the element itself. They raise the baseline of the element (or the bottom, if it has no baseline) the specified amount above the baseline of the parent. Negative values are possible. E.g., a value of '-100%' will lower the element so that the baseline of the element ends up where the baseline of the next line should have been. This allows precise control over the vertical position of elements (such as images that are used in place of letters) that don't have a baseline.
It is expected that a future version of CSS will allow <length> as a value on this property.
Value: capitalize | uppercase | lowercase | none
Initial: none
Applies to: all elements
Inherited: yes
Percentage values: N/A
The actual transformation in each case is human language dependent. See [4] for ways to find the language of an element.
H1 { text-transform: uppercase }
The example above would put 'H1' elements in uppercase text.
CSS1 core: UAs may ignore 'text-transform' (i.e., treat it as 'none') for characters that are not from the Latin-1 repertoire and for elements in languages for which the transformation is different from that specified by the case-conversion tables of Unicode [8].
Value: left | right | center | justify
Initial: UA specific
Applies to: block-level elements
Inherited: yes
Percentage values: N/A
This property describes how text is aligned within the element. The actual justification algorithm used is UA and human language dependent.
Example:
DIV.center { text-align: center }
Since 'text-align' inherits, all block-level elements inside the 'DIV' element with 'CLASS=center' will be centered. Note that alignments are relative to the width of the element, not the canvas. If 'justify' is not supported, the UA will supply a replacement. Typically, this will be 'left' for western languages.
CSS1 core: UAs may treat 'justify' as 'left' or 'right', depending on whether the element's default writing direction is left-to-right or right-to-left, respectively.
Value: <length> | <percentage>
Initial: 0
Applies to: block-level elements
Inherited: yes
Percentage values: refer to parent element's width
The property specifies the indentation that appears before the first formatted line. The value of 'text-indent' may be negative, but there may be implementation-specific limits. An indentation is not inserted in the middle of an element that was broken by another (such as 'BR' in HTML).
Example:
P { text-indent: 3em }
Value: normal | <number> | <length> |
<percentage>
Initial: normal
Applies to: all elements
Inherited: yes
Percentage values: relative to the font size of the element itself
The property sets the distance between two adjacent lines' baselines.
When a numerical value is specified, the line height is given by the font size of the current element multiplied with the numerical value. This differs from a percentage value in the way it inherits: when a numerical value is specified, child elements will inherit the factor itself, not the resultant value (as is the case with percentage and other units).
Negative values are not allowed.
The three rules in the example below have the same resultant line height:
DIV { line-height: 1.2; font-size: 10pt } /* number */ DIV { line-height: 1.2em; font-size: 10pt } /* length */ DIV { line-height: 120%; font-size: 10pt } /* percentage */
A value of 'normal' sets the 'line-height' to a reasonable value for the element's font. It is suggested that UAs set the 'normal' value to be a number in the range of 1.0 to 1.2.
See the section 4.4 for a description on how 'line-height' influences the formatting of a block-level element.
The box properties set the size, circumference and position of the boxes that represent elements. See the formatting model (section 4) for examples on how to use the box properties.
The margin properties set the margin of an element. The 'margin' property sets the margin for all four sides while the other margin properties only set their respective side.
The padding properties describe how much space to insert between the border and the content (e.g., text or image). The 'padding' property sets the padding for all four sides while the other padding properties only set their respective side.
The border properties set the borders of an element. Each element has four borders, one on each side, that are defined by their width, color and style.
The 'width' and 'height' properties set the size of the box, and the 'float' and 'clear' properties can alter the position of elements.
Value: <length> | <percentage> | auto
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of the closest block-level ancestor
This property sets the top margin of an element:
H1 { margin-top: 2em }
A negative value is allowed, but there may be implementation-specific limits.
Value: <length> | <percentage> | auto
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the right margin of an element:
H1 { margin-right: 12.3% }
A negative value is allowed, but there may be implementation-specific limits.
Value: <length> | <percentage> | auto
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the bottom margin of an element:
H1 { margin-bottom: 3px }
A negative value is allowed, but there may be implementation-specific limits.
Value: <length> | <percentage> | auto
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the left margin of an element:
H1 { margin-left: 2em }
A negative value is allowed, but there may be implementation-specific limits.
Value: [ <length> | <percentage> | auto ]{1,4}
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
The 'margin' property is a shorthand property for setting 'margin-top', 'margin-right', 'margin-bottom' and 'margin-left' at the same place in the style sheet.
If four length values are specified they apply to top, right, bottom and left respectively. If there is only one value, it applies to all sides, if there are two or three, the missing values are taken from the opposite side.
BODY { margin: 2em } /* all margins set to 2em */ BODY { margin: 1em 2em } /* top & bottom = 1em, right & left = 2em */ BODY { margin: 1em 2em 3em } /* top=1em, right=2em, bottom=3em, left=2em */
The last rule of the example above is equivalent to the example below:
BODY { margin-top: 1em; margin-right: 2em; margin-bottom: 3em; margin-left: 2em; /* copied from opposite side (right) */ }
Negative margin values are allowed, but there may be implementation-specific limits.
Value: <length> | <percentage>
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the top padding of an element.
BLOCKQUOTE { padding-top: 0.3em }
Padding values cannot be negative.
Value: <length> | <percentage>
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the right padding of an element.
BLOCKQUOTE { padding-right: 10px }
Padding values cannot be negative.
Value: <length> | <percentage>
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the bottom padding of an element.
BLOCKQUOTE { padding-bottom: 2em }
Padding values cannot be negative.
Value: <length> | <percentage>
Initial: 0
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
This property sets the left padding of an element.
BLOCKQUOTE { padding-left: 20% }
Padding values cannot be negative.
Value: [ <length> | <percentage> ]{1,4}
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: refer to width of closest block-level ancestor
The 'padding' property is a shorthand property for setting 'padding-top', 'padding-right', 'padding-bottom' and 'padding-left' at the same place in the style sheet.
If four values are specified they apply to top, right, bottom and left respectively. If there is only one value, it applies to all sides, if there are two or three, the missing values are taken from the opposite side.
The surface of the padding area is set with the 'background' property:
H1 { background: white; padding: 1em 2em; }
The example above sets a '1em' padding vertically ('padding-top' and 'padding-bottom') and a '2em' padding horizontally ('padding-right' and 'padding-left'). The 'em' unit is relative to the element's font size: '1em' is equal to the size of the font in use.
Padding values cannot be negative.
Value: thin | medium | thick | <length>
Initial: 'medium'
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the width of an element's top border. The width of the keyword values are UA dependent, but the following holds: 'thin' <= 'medium' <= 'thick'.
The keyword widths are constant throughout a document:
H1 { border: solid thick red } P { border: solid thick blue }
In the example above, 'H1' and 'P' elements will have the same border width regardless of font size. To achieve relative widths, the 'em' unit can be used:
H1 { border: solid 0.5em }
Border widths cannot be negative.
Value: thin | medium | thick | <length>
Initial: 'medium'
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the width of an element's right border. Otherwise it is equivalent to the 'border-top-width'.
Value: thin | medium | thick | <length>
Initial: 'medium'
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the width of an element's bottom border. Otherwise it is equivalent to the 'border-top-width'.
Value: thin | medium | thick | <length>
Initial: 'medium'
Applies to: all elements
Inherited: no
Percentage values: N/A
This property sets the width of an element's left border. Otherwise it is equivalent to the 'border-top-width'.
Value: [thin | medium | thick | <length>]{1,4}
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
This property is a shorthand property for setting 'border-width-top', 'border-width-right', 'border-width-bottom' and 'border-width-left' at the same place in the style sheet.
There can be from one to four values, with the following interpretation:
In the examples below, the comments indicate the resulting widths of the top, right, bottom and left borders:
H1 { border-width: thin } /* thin thin thin thin */
H1 { border-width: thin thick } /* thin thick thin thick */
H1 { border-width: thin thick medium } /* thin thick medium thin */
H1 { border-width: thin thick medium thin } /* thin thick medium thin */
Border widths cannot be negative.
Value: <color>{1,4}
Initial: the value of the 'color' property
Applies to: all elements
Inherited: no
Percentage values: N/A
The 'border-color' property sets the color of the four borders. 'border-color' can have from one to four values, and the values are set on the different sides as for 'border-width' above.
If no color value is specified, the value of the 'color' property of the element itself will take its place:
P { color: black; background: white; border: solid; }
In the above example, the border will be a solid black line.
Value: none | dotted | dashed | solid | double | groove | ridge
| inset | outset
Initial: none
Applies to: all elements
Inherited: no
Percentage values: N/A
The 'border-style' property sets the style of the four borders. It can have from one to four values, and the values are set on the different sides as for 'border-width' above.
#xy34 { border-style: solid dotted }
In the above example, the horizontal borders will be 'solid' and the vertical borders will be 'dotted'.
Since the initial value of the border styles is 'none', no borders will be visible unless the border style is set.
The border styles mean:
CSS1 core: UAs may interpret all of 'dotted', 'dashed', 'double', 'groove', 'ridge', 'inset' and 'outset' as 'solid'.
Value: <border-top-width> || <border-style> ||
<color>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
This is a shorthand property for setting the width, style and color of an element's top border.
H1 { border-bottom: thick solid red }
The above rule will set the width, style and color of the border below the H1 element. Omitted values will be set to their initial values:
H1 { border-bottom: thick solid }
Since the color value is omitted in the example above, the border color will be the same as the 'color' value of the element itself.
Note that while the 'border-style' property accepts up to four values, this property only accepts one style value.
Value: <border-right-width> || <border-style> ||
<color>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
This is a shorthand property for setting the width, style and color of an element's right border. Otherwise it is equivalent to the 'border-top'.
Value: <border-bottom-width> || <border-style> ||
<color>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
This is a shorthand property for setting the width, style and color of an element's bottom border. Otherwise it is equivalent to the 'border-top'.
Value: <border-left-width> || <border-style> ||
<color>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
This is a shorthand property for setting the width, style and color of an element's left border. Otherwise it is equivalent to the 'border-top'.
Value: <border-width> || <border-style> ||
<color>
Initial: not defined for shorthand properties
Applies to: all elements
Inherited: no
Percentage values: N/A
The 'border' property is a shorthand property for setting the same width, color and style on all four borders of an element. For example, the first rule below is equivalent to the set of four rules shown after it:
P { border: solid red } P { border-top: solid red; border-right: solid red; border-bottom: solid red; border-left: solid red }
Unlike the shorthand 'margin' and 'padding' properties, the 'border' property cannot set different values on the four borders. To do so, one or more of the other border properties must be used.
Since the properties to some extent have overlapping functionality, the order in which the rules are specified becomes important. Consider this example:
BLOCKQUOTE { border-color: red; border-left: double color: black; }
In the above example, the color of the left border will be black, while the other borders are red. This is due to 'border-left' setting the width, style and color. Since the color value is not specified on the 'border-left' property, it will be taken from the 'color' property. The fact that the 'color' property is set after the 'border-left' property is not relevant.
Note that while the 'border-width' property accepts up to four length values, this property only accepts one.
Value: <length> | <percentage> | auto
Initial: auto
Applies to: block-level and replaced elements
Inherited: no
Percentage values: refer to parent element's width
This property can be applied to text elements, but it is most useful with replaced elements such as images. The width is to be enforced by scaling the image if necessary. When scaling, the aspect ratio of the image is preserved if the 'height' property is 'auto'.
Example:
IMG.icon { width: 100px }
If the 'width' and 'height' of a replaced element are both 'auto', these properties will be set to the intrinsic dimensions of the element.
Negative values are not allowed.
See the formatting model (section 4) for a description of the relationship between this property and the margin and padding.
Value: <length> | auto
Initial: auto
Applies to: block-level and replaced elements
Inherited: no
Percentage values: N/A
This property can be applied to text, but it is most useful with replaced elements such as images. The height is to be enforced by scaling the image if necessary. When scaling, the aspect ratio of the image is preserved if the 'width' property is 'auto'.
Example:
IMG.icon { height: 100px }
If the 'width' and 'height' of a replaced element are both 'auto', these properties will be set to the intrinsic dimensions of the element.
If applied to a textual element, the height can be enforced with e.g. a scrollbar.
Negative values are not allowed.
CSS1 core: UAs may ignore the 'height' property (i.e., treat it as 'auto') if the element is not a replaced element.
Value: left | right | none
Initial: none
Applies to: all elements
Inherited: no
Percentage values: N/A
With the value 'none', the element will be displayed where it appears in the text. With a value of 'left' ('right') the element will be moved to the left (right) and the text will wrap on the right (left) side of the element. With a value of 'left' or 'right', the element is treated as block-level (i.e. the 'display' property is ignored). See section 4.1.4 for a full specification.
IMG.icon { float: left; margin-left: 0; }
The above example will place all IMG elements with 'CLASS=icon' along the left side of the parent element.
This property is most often used with inline images, but also applies to text elements.
Value: none | left | right | both
Initial: none
Applies to: all elements
Inherited: no
Percentage values: N/A
This property specifies if an element allows floating elements on its sides. More specifically, the value of this property lists the sides where floating elements are not accepted. With 'clear' set to 'left', an element will be moved below any floating element on the left side. With 'clear' set to 'none', floating elements are allowed on all sides. Example:
H1 { clear: left }
These properties classify elements into categories more than they set specific visual parameters.
The list-style properties describe how list items (i.e. elements with a 'display' value of 'list-item') are formatted. The list-style properties can be set on any element, and it will inherit normally down the tree. However, they will only be have effect on elements with a 'display' value of 'list-item'. In HTML this is typically the case for the 'LI' element.
Value: block | inline | list-item | none
Initial: block
Applies to: all elements
Inherited: no
Percentage values: N/A
This property describes how/if an element is displayed on the canvas (which may be on a printed page, a computer display etc.).
An element with a 'display' value of 'block' opens a new box. The box is positioned relative to adjacent boxes according to the CSS formatting model. Typically, elements like 'H1' and 'P' are of type 'block'. A value of 'list-item' is similar to 'block' except that a list-item marker is added. In HTML, 'LI' will typically have this value.
An element with a 'display' value of 'inline' results in a new inline box on the same line as the previous content. The box is dimensioned according to the formatted size of the content. If the content is text, it may span several lines, and there will be a box on each line. The margin, border and padding properties apply to 'inline' elements, but will not have any effect at the line breaks.
A value of 'none' turns off the display of the element, including children elements and the surrounding box.
P { display: block } EM { display: inline } LI { display: list-item } IMG { display: none }
The last rule turns off the display of images.
The initial value of 'display' is 'block', but a UA will typically have default values for all HTML elements according to the suggested rendering of elements in the HTML specification [2].
CSS1 core: UAs may ignore 'display' and use only the UA's default values. (See section 7.)
Value: normal | pre | nowrap
Initial: normal
Applies to: block-level elements
Inherited: yes
Percentage values: N/A
This property declares how whitespace inside the element is handled: the 'normal' way (where whitespace is collapsed), as 'pre' (which behaves like the 'PRE' element in HTML) or as 'nowrap' (where wrapping is done only through BR elements):
PRE { white-space: pre } P { white-space: normal }
The initial value of 'white-space' is 'normal', but a UA will typically have default values for all HTML elements according to the suggested rendering of elements in the HTML specification [2].
CSS1 core: UAs may ignore the 'white-space' property in author's and reader's style sheets, and use the UA's default values instead. (See section 7.)
Value: disc | circle | square | decimal | lower-roman | upper-roman
| lower-alpha | upper-alpha | none
Initial: disc
Applies to: elements with 'display' value 'list-item'
Inherited: yes
Percentage values: N/A
This property is used to determine the appearance of the list-item marker if 'list-style-image' is 'none' or if the image pointed to by the URL cannot be displayed.
OL { list-style-type: decimal } /* 1 2 3 4 5 etc. */ OL { list-style-type: lower-alpha } /* a b c d e etc. */ OL { list-style-type: lower-roman } /* i ii iii iv v etc. */
Value: <url> | none
Initial: none
Applies to: elements with 'display' value 'list-item'
Inherited: yes
Percentage values: N/A
This property sets the image that will be used as the list-item marker. When the image is available it will replace the marker set with the 'list-style-type' marker.
UL { list-style-image: url(http://png.com/ellipse.png) }
Value: inside | outside
Initial: outside
Applies to: elements with 'display' value 'list-item'
Inherited: yes
Percentage values: N/A
The value of 'list-style-position' determines how the list-item marker is drawn with regard to the content. For a formatting example see section 4.1.3.
Value: [disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none] || [inside | outside] || [<url> | none]
Initial: not defined for shorthand properties
Applies to: elements with 'display' value 'list-item'
Inherited: yes
Percentage values: N/A
The 'list-style' property is a shorthand notation for setting the three properties 'list-style-type', 'list-style-image' and 'list-style-position' at the same place in the style sheet.
UL { list-style: upper-roman inside } UL UL { list-style: circle outside } LI.square { list-style: square }
Setting 'list-style' directly on 'LI' elements can have unexpected results. Consider:
<STYLE TYPE="text/css"> OL.alpha LI { list-style: lower-alpha } UL LI { list-style: disc } </STYLE> <BODY> <OL CLASS=alpha> <LI>level 1 <UL> <LI>level 2 </UL> </OL> </BODY>
Since the specificity (as defined in the cascading order) is higher for the first rule in the style sheet in the example above, it will override the second rule on all 'LI' elements and only 'lower-alpha' list styles will be used. It is therefore recommended to set 'list-style' only on the list type elements:
OL.alpha { list-style: lower-alpha } UL { list-style: disc }
In the above example, inheritance will transfer the 'list-style' values from 'OL' and 'UL' elements to 'LI' elements.
A URL value can be combined with any other value:
UL { list-style: url(http://png.com/ellipse.png) disc }
In the example above, the 'disc' will be used when the image is unavailable.
The format of a length value is an optional sign character ('+' or '-', with '+' being the default) immediately followed by a number (with or without a decimal point) immediately followed by a unit identifier (a two-letter abbreviation). After a '0' number, the unit identifier is optional.
Some properties allow negative length units, but this may complicate the formatting model and there may be implementation-specific limits. If a negative length value cannot be supported, it should be clipped to the nearest value that can be supported.
There are two types of length units: relative and absolute. Relative units specify a length relative to another length property. Style sheets that use relative units will more easily scale from one medium to another (e.g. from a computer display to a laser printer). Percentage units (described below) and keyword values (e.g. 'x-large') offer similar advantages.
These relative units are supported:
H1 { margin: 0.5em } /* ems, the height of the element's font */ H1 { margin: 1ex } /* x-height, ~ the height of the letter 'x' */ P { font-size: 12px } /* pixels, relative to canvas */
The relative units 'em' and 'ex' are relative to the font size of the element itself. The only exception to this rule in CSS1 is the 'font-size' property where 'em' and 'ex' values refer to the font size of the parent element.
Pixel units, as used in the last rule, are relative to the resolution of the canvas, i.e. most often a computer display. If the pixel density of the output device is very different from that of a typical computer display, the UA should rescale pixel values. The suggested reference pixel is the visual angle of one pixel on a device with a pixel density of 90dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is about 0.0227 degrees.
Child elements inherit the computed value, not the relative value:
BODY { font-size: 12pt; text-indent: 3em; /* i.e. 36pt */ } H1 { font-size: 15pt }
In the example above, the 'text-indent' value of 'H1' elements will be 36pt, not 45pt.
Absolute length units are only useful when the physical properties of the output medium are known. These absolute units are supported:
H1 { margin: 0.5in } /* inches, 1in = 2.54cm */ H2 { line-height: 3cm } /* centimeters */ H3 { word-spacing: 4mm } /* millimeters */ H4 { font-size: 12pt } /* points, 1pt = 1/72 in */ H4 { font-size: 1pc } /* picas, 1pc = 12pt */
In cases where the specified length cannot be supported, UAs should try to approximate. For all CSS1 properties, further computations and inheritance should be based on the approximated value.
The format of a percentage value is an optional sign character ('+' or '-', with '+' being the default) immediately followed by a number (with or without a decimal point) immediately followed by '%'.
Percentage values are always relative to another value, for example a length unit. Each property that allows percentage units also defines what value the percentage value refer to. Most often this is the font size of the element itself:
P { line-height: 120% } /* 120% of the element's 'font-size' */
In all inherited CSS1 properties, if the value is specified as a percentage, child elements inherit the resultant value, not the percentage value.
A color is a either a keyword or a numerical RGB specification.
The suggested list of keyword color names is: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. These 16 colors are taken from the Windows VGA palette, and their RGB values are not defined in this specification.
BODY {color: black; background: white } H1 { color: maroon } H2 { color: olive }
The RGB color model is being used in numerical color specifications. These examples all specify the same color:
EM { color: #f00 } /* #rgb */ EM { color: #ff0000 } /* #rrggbb */ EM { color: rgb(255,0,0) } /* integer range 0 - 255 */ EM { color: rgb(100%, 0%, 0%) } /* float range 0.0% - 100.0% */
The format of an RGB value in hexadecimal notation is a '#' immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This makes sure that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.
The format of an RGB value in the functional notation is 'rgb(' followed by a comma-separated list of three numerical values (either three integer values in the range of 0-255, or three percentage values in the range of 0.0% to 100.0%) followed by ')'. Whitespace characters are allowed around the numerical values.
Values outside the numerical ranges should be clipped. The three rules below are therefore equivalent:
EM { color: rgb(255,0,0) } /* integer range 0 - 255 */ EM { color: rgb(300,0,0) } /* clipped to 255 */ EM { color: rgb(110%, 0%, 0%) } /* clipped to 100% */
RGB colors are specified in the sRGB color space [9]. UAs may vary in the fidelity with which they represent these colors, but use of sRGB provides an unambiguous and objectively measurable definition of what the color should be, which can be related to international standards [10].
UAs may limit their efforts in displaying colors to performing a gamma-correction on them. sRGB specifies a display gamma of 2.2 under specified viewing conditions. UAs adjust the colors given in CSS such that, in combination with an output device's "natural" display gamma, an effective display gamma of 2.2 is produced. Appendix D gives further details of this. Note that only colors specified in CSS are affected; e.g., images are expected to carry their own color information.
A Uniform Resource Locator (URL) is identified with a functional notation:
BODY { background: url(http://www.bg.com/pinkish.gif) }
The format of a URL value is 'url(' followed by optional white space followed by an optional single quote (') or double quote (") character followed by the URL itself (as defined in [11]) followed by an optional single quote (') or double quote (") character followed by optional whitespace followed by ')'. Quote characters that are not part of the URL itself must be balanced.
Parentheses, commas, whitespace characters, single quotes (') and double quotes (") appearing in a URL must be escaped with a backslash: '\(', '\)', '\,'.
Partial URLs are interpreted relative to the source of the style sheet, not relative to the document:
BODY { background: url(yellow) }
A User Agent that uses CSS1 to display documents conforms to the CSS1 specification if it:
A User Agent that outputs CSS1 style sheets conforms to the CSS1 specification if it:
A User Agent that uses CSS1 to display documents and outputs CSS1 style sheets conforms to the CSS1 specification if it meets both sets of conformance requirements.
A UA does not have to implement all the functionality of CSS1: it can conform to CSS1 by implementing the core functionality. The core functionality consists of the whole CSS1 specification except those parts explicitly excluded. In the text, those parts are marked with "CSS1 core:" followed by an explanation of what functionality is outside the core functionality. The set of features excluded from the core functionality is called CSS1 advanced features.
This section only defines conformance to CSS1. There will be other levels of CSS in the future that may require a UA to implement a different set of features in order to conform.
Examples of constraints of the presentation medium are: limited resources (fonts, color) and limited resolution (so margins may not be accurate). In these cases, the UA should approximate the style sheet values. Also, different user interface paradigms may have their own constraints: a VR browser may rescale the document based on its "distance" from the user.
UAs may offer readers additional choices on presentation. For example, the UA may provide options for readers with visual impairments or may provide the choice to disable blinking.
Note that CSS1 does not specify all aspects of formatting. E.g., the UA is free to select a letter-spacing algorithm.
This specification also recommends, but doesn't require, that a UA:
The above conformance rules describe only functionality, not user interface.
This specification defines CSS level 1. It is expected that higher levels of CSS, with additional features, will be defined in the future. To ensure that UAs supporting just CSS1 will be able to read style sheets containing higher level features, this section defines what the UA does when it encounters certain constructs that are not valid in CSS level 1.
H1 { color: red; rotation: 70deg }
the UA will treat this as if the style sheet had been
H1 { color: red; }
IMG { float: left } /* CSS1 */ IMG { float: left top } /* "top" is not a value of 'float' */ IMG { background: "red" } /* keywords cannot be quoted in CSS1 */ IMG { border-width: 3 } /* a unit must be specified for length values */
In the above example, a CSS1 parser would honor the first rule and ignore the rest, as if the style sheet had been
IMG { float: left } IMG { } IMG { } IMG { }
A UA conforming to a future CSS specification may accept one or more of the other rules as well.
@three-dee { @background-lighting { azimuth: 30deg; elevation: 190deg; } H1 { color: red } } H1 {color: blue}
The '@three-dee' is illegal according to CSS1. Therefore, the whole at-rule (up to, and including, the third right curly brace) is ignored. The CSS1 UA skips it, effectively reducing the style sheet to:
H1 {color: blue}
In more detail:
A CSS style sheet, for any version of CSS, consists of a list of statements. There are two kinds of statements: at-rules and rulesets. There may be whitespace (spaces, tabs, newlines) around the statements.
CSS style sheets are often embedded in HTML documents, and to be able to hide style sheets from older UAs, it is convenient put the style sheets inside HTML comments. The HTML comment tokens "<!--" and "-->" may occur before, after, and in between the statements. They may have whitespace around them.
At-rules start with an at-keyword, which is an identifier with an '@' at the start (for example: '@import', '@page'). An identifier consists of letters, digits, dashes and escaped characters (defined below).
An at-rule consists of everything up to and including the next semicolon (;) or the next block (defined shortly), whichever comes first. A CSS1 UA that encounters an at-rule that starts with an at-keyword other than '@import' ignores the whole of the at-rule and continue parsing after it. It also ignores any at-rule that starts with '@import' if it doesn't occur at the top of the style sheet, i.e., if it occurs after any rules (even ignored rules). Here is an example.
Assume a CSS1 parser encounters this style sheet:
@import "subs.css"; H1 { color: blue } @import "list.css";
The second '@import' is illegal according to CSS1. The CSS1 parser skips the whole at-rule, effectively reducing the style sheet to:
@import "subs.css"; H1 {color: blue}
A block starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there may be any characters, except that parentheses (()), brackets ([]) and braces ({}) always occur in matching pairs and may be nested. Single (') and double quotes (") also occur in matching pairs, and characters between them are parsed as a string (see the tokenizer in appendix B for a definition of string). Here is an example of a block; note that the right brace between the quotes does not match the opening brace of the block, and that the second single quote is an escaped character, and thus doesn't match the opening quote:
{ causta: "}" + ({7} * '\'') }
A ruleset consists of a selector-string followed by a declaration-block. The selector-string consists of everything up to (but not including) the first left curly brace ({). A ruleset that starts with a selector-string that is not valid CSS1 is skipped.
For example, assume a CSS1 parser encounters this style sheet:
H1 { color: blue } P[align], UL { color: red; font-size: large } P EM { font-weight: bold }
The second line contains a selector-string that is illegal in CSS1. The CSS1 UA will skip the ruleset, reducing the style sheet to:
H1 { color: blue } P EM { font-weight: bold }
A declaration-block starts with a left curly brace ({) and ends with the matching right curly brace (}). In between there is a list of zero or more declarations, separated by semicolons (;).
A declaration consists of a property, a colon (:) and a value. Around each of these there may be whitespace. A property is an identifier, as defined earlier. Any character may occur in the value, but parentheses (()), brackets ([]), braces ({}), single quotes (') and double quotes (") must come in matching pairs. Parentheses, brackets, and braces may be nested. Inside the quotes, characters are parsed as a string.
To ensure that new properties and new values for existing properties can be added in the future, a UA must skip a declaration with an invalid property name or an invalid value. Every CSS1 property has its own syntactic and semantic restrictions on the values it accepts.
For example, assume a CSS1 parser encounters this style sheet:
H1 { color: red; font-style: 12pt } P { color: blue; font-vendor: any; font-variant: small-caps } EM EM { font-style: normal }
The second declaration on the first line has an invalid value '12pt'. The second declaration on the second line contains an undefined property 'font-vendor'. The CSS1 parser will skip these declarations, reducing the style sheet to:
H1 { color: red; } P { color: blue; font-variant: small-caps } EM EM { font-style: normal }
Comments (see section 1.7) can occur anywhere where whitespace can occur and are considered to be whitespace. CSS1 defines additional places where whitespace can occur (such as inside values) and comments are allowed there as well.
The following rules always hold:
Note: The CLASS attribute of HTML allows more characters in a class name than the set allowed for selectors above. In CSS1, these characters have to be escaped or written as Unicode numbers: "B&W?" can be written as "B\&W\?" or "B\26W\3F", "κουρος" (Greek: "kouros") has to be written as "\3BA\3BF\3C5\3C1\3BF\3C2". It is expected that in later versions of CSS more characters can be entered directly.
Appendix B gives a grammar for CSS1.
[1] W3C resource page on web style sheets (http://www.w3.org/Style)
[2] "HTML 4.0 Specification", D. Raggett, A. Le Hors, I. Jacobs, December 1997. Available at http://www.w3.org/TR/REC-html40/.
[3] T Berners-Lee, D Connolly: "Hypertext Markup Language - 2.0", RFC 1866, MIT/W3C, November 1995. The specification is also available in hypertext form (http://www.w3.org/MarkUp/html-spec/html-spec_toc.html)
[4] F Yergeau, G Nicol, G Adams, M Dürst: "Internationalization of the Hypertext Markup Language" (ftp://ds.internic.net/rfc/rfc2070.txt).
[5] ISO 8879:1986. Information Processing - Text and Office Systems - Standard Generalized Markup Language (SGML)
[6] ISO/IEC 10179:1996 Information technology -- Processing languages -- Document Style Semantics and Specification Language (DSSSL).
[7] ISO/IEC 9899:1990 Programming languages -- C.
[8] The Unicode Consortium, "The Unicode Standard -- Worldwide Character Encoding -- Version 1.0", Addison-Wesley, Volume 1, 1991, Volume 2, 1992.
[9] "A Standard Default color Space for the Internet", version 1.10, M. Stokes, M. Anderson, S. Chandrasekar, and R. Motta, 5 November 1996.
[10] CIE Publication 15.2-1986, "Colorimetry, Second Edition", ISBN 3-900-734-00-3 (http://www.hike.te.chiba-u.ac.jp/ikeda/CIE/publ/abst/15-2-86.html)
[11] T Berners-Lee, L Masinter, M McCahill: "Uniform Resource Locators (URL)", RFC 1738, CERN, Xerox Corporation, University of Minnesota, December 1994
[12] "PNG (Portable Network Graphics) Specification, Version 1.0 specification" (http://www.w3.org/TR/REC-png-multi.html)
[13] Charles A. Poynton: "Gamma correction on the Macintosh Platform" (ftp://ftp.inforamp.net/pub/users/poynton/doc/Mac/Mac_gamma.pdf)
[14] International Color Consortium: "ICC Profile Format Specification, version 3.2", 1995 (ftp://sgigate.sgi.com/pub/icc/ICC32.pdf)
[15] S C Johnson: "YACC - Yet another compiler compiler", Technical Report, Murray Hill, 1975
[16] "Flex: The Lexical Scanner Generator", Version 2.3.7, ISBN 1882114213
During the short life of HTML, there have been several style sheet proposals to which this proposal is indebted. Especially the proposals from Robert Raisch, Joe English and Pei Wei were influential.
A number of people have contributed to the development of CSS1. We would especially like to thank: Terry Allen, Murray Altheim, Glenn Adams, Walter Bender, Tim Berners-Lee, Yves Bertot, Scott Bigham, Steve Byrne, Robert Cailliau, James Clark, Daniel Connolly, Donna Converse, Adam Costello, Todd Fahrner, Todd Freter, Roy Fielding, Neil Galarneau, Wayne Gramlich, Phill Hallam-Baker, Philipp Hoschka, Kevin Hughes, Scott Isaacs, Tony Jebson, William Johnston, Gilles Kahn, Philippe Kaplan, Phil Karlton, Evan Kirshenbaum, Yves Lafon, Murray Maloney, Lou Montulli, Colas Nahaboo, Henrik Frystyk Nielsen, David Perrell, William Perry, Scott Preece, Paul Prescod, Liam Quin, Vincent Quint, Jenny Raggett, Thomas Reardon, Cécile Roisin, Michael Seaton, David Seibert, David Siegel, David Singer, Benjamin Sittler, Jon Smirl, Charles Peyton Taylor, Irène Vatton, Daniel Veillard, Mandira Virmani, Greg Watkins, Mike Wexler, Lydja Williams, Brian Wilson, Chris Wilson, Lauren Wood and Stephen Zilles.
Three people deserve special mentioning: Dave Raggett (for his encouragement and work on HTML3), Chris Lilley (for his continued contributions, especially in the area of colors and fonts) and Steven Pemberton (for his organizational as well as creative skills).
(This appendix is informative, not normative)
The following style sheet is written according to the suggested rendering in the HTML 2.0 [3] specification. Some styles, e.g. colors, have been added for completeness. It is suggested that a style sheet similar to the one below is used as the UA default.
BODY {
margin: 1em;
font-family: serif;
line-height: 1.1;
background: white;
color: black;
}
H1, H2, H3, H4, H5, H6, P, UL, OL, DIR, MENU, DIV,
DT, DD, ADDRESS, BLOCKQUOTE, PRE, BR, HR, FORM, DL {
display: block }
B, STRONG, I, EM, CITE, VAR, TT, CODE, KBD, SAMP,
IMG, SPAN { display: inline }
LI { display: list-item }
H1, H2, H3, H4 { margin-top: 1em; margin-bottom: 1em }
H5, H6 { margin-top: 1em }
H1 { text-align: center }
H1, H2, H4, H6 { font-weight: bold }
H3, H5 { font-style: italic }
H1 { font-size: xx-large }
H2 { font-size: x-large }
H3 { font-size: large }
B, STRONG { font-weight: bolder } /* relative to the parent */
I, CITE, EM, VAR, ADDRESS, BLOCKQUOTE { font-style: italic }
PRE, TT, CODE, KBD, SAMP { font-family: monospace }
PRE { white-space: pre }
ADDRESS { margin-left: 3em }
BLOCKQUOTE { margin-left: 3em; margin-right: 3em }
UL, DIR { list-style: disc }
OL { list-style: decimal }
MENU { margin: 0 } /* tight formatting */
LI { margin-left: 3em }
DT { margin-bottom: 0 }
DD { margin-top: 0; margin-left: 3em }
HR { border-top: solid } /* 'border-bottom' could also have been used */
A:link { color: blue } /* unvisited link */
A:visited { color: red } /* visited links */
A:active { color: lime } /* active links */
/* setting the anchor border around IMG elements
requires contextual selectors */
A:link IMG { border: 2px solid blue }
A:visited IMG { border: 2px solid red }
A:active IMG { border: 2px solid lime }
(This appendix is normative)
The minimal CSS (i.e., any version of CSS) grammar that all implementations need to support is defined in section 7. The grammar below defines a much smaller language, a language that defines the syntax of CSS1.
It is in some sense, however, still a superset of CSS1: there are additional semantic constraints not expressed in this grammar. A conforming UA must also adhere to the forward-compatible parsing rules (section 7.1), the property and value notation (section 5) and the unit notation (section 6). In addition, HTML imposes restrictions, e.g., on the possible values of the CLASS attribute.
The grammar below is LL(1) (but note that most UA's should not use it directly, since it doesn't express the parsing conventions, only the CSS1 syntax). The format of the productions is optimized for human consumption and some shorthand notation beyond yacc [15] is used:
* : 0 or more + : 1 or more ? : 0 or 1 | : separates alternatives [] : grouping
The productions are:
stylesheet : [CDO|CDC]* [ import [CDO|CDC]* ]* [ ruleset [CDO|CDC]* ]* ; import : IMPORT_SYM [STRING|URL] ';' /* E.g., @import url(fun.css); */ ; unary_operator : '-' | '+' ; operator : '/' | ',' | /* empty */ ; property : IDENT ; ruleset : selector [ ',' selector ]* '{' declaration [ ';' declaration ]* '}' ; selector : simple_selector+ [ pseudo_element | solitary_pseudo_element ]? | solitary_pseudo_element ; /* An "id" is an ID that is attached to an element type ** on its left, as in: P#p007 ** A "solitary_id" is an ID that is not so attached, ** as in: #p007 ** Analogously for classes and pseudo-classes. */ simple_selector : element_name id? class? pseudo_class? /* eg: H1.subject */ | solitary_id class? pseudo_class? /* eg: #xyz33 */ | solitary_class pseudo_class? /* eg: .author */ | solitary_pseudo_class /* eg: :link */ ; element_name : IDENT ; pseudo_class /* as in: A:link */ : LINK_PSCLASS_AFTER_IDENT | VISITED_PSCLASS_AFTER_IDENT | ACTIVE_PSCLASS_AFTER_IDENT ; solitary_pseudo_class /* as in: :link */ : LINK_PSCLASS | VISITED_PSCLASS | ACTIVE_PSCLASS ; class /* as in: P.note */ : CLASS_AFTER_IDENT ; solitary_class /* as in: .note */ : CLASS ; pseudo_element /* as in: P:first-line */ : FIRST_LETTER_AFTER_IDENT | FIRST_LINE_AFTER_IDENT ; solitary_pseudo_element /* as in: :first-line */ : FIRST_LETTER | FIRST_LINE ; /* There is a constraint on the id and solitary_id that the ** part after the "#" must be a valid HTML ID value; ** e.g., "#x77" is OK, but "#77" is not. */ id : HASH_AFTER_IDENT ; solitary_id : HASH ; declaration : property ':' expr prio? | /* empty */ /* Prevents syntax errors... */ ; prio : IMPORTANT_SYM /* !important */ ; expr : term [ operator term ]* ; term : unary_operator? [ NUMBER | STRING | PERCENTAGE | LENGTH | EMS | EXS | IDENT | hexcolor | URL | RGB ] ; /* There is a constraint on the color that it must ** have either 3 or 6 hex-digits (i.e., [0-9a-fA-F]) ** after the "#"; e.g., "#000" is OK, but "#abcd" is not. */ hexcolor : HASH | HASH_AFTER_IDENT ;
The following is the tokenizer, written in flex [16] notation. Note that this assumes an 8-bit implementation of flex. The tokenizer is case-insensitive (flex command line option -i).
unicode \\[0-9a-f]{1,4} latin1 [¡-ÿ] escape {unicode}|\\[ -~¡-ÿ] stringchar {escape}|{latin1}|[ !#$%&(-~] nmstrt [a-z]|{latin1}|{escape} nmchar [-a-z0-9]|{latin1}|{escape} ident {nmstrt}{nmchar}* name {nmchar}+ d [0-9] notnm [^-a-z0-9\\]|{latin1} w [ \t\n]* num {d}+|{d}*\.{d}+ string \"({stringchar}|\')*\"|\'({stringchar}|\")*\' %x COMMENT %s AFTER_IDENT %% "/*" {BEGIN(COMMENT);} <COMMENT>"*/" {BEGIN(0);} <COMMENT>\n {/* ignore */} <COMMENT>. {/* ignore */} @import {BEGIN(0); return IMPORT_SYM;} "!"{w}important {BEGIN(0); return IMPORTANT_SYM;} {ident} {BEGIN(AFTER_IDENT); return IDENT;} {string} {BEGIN(0); return STRING;} {num} {BEGIN(0); return NUMBER;} {num}"%" {BEGIN(0); return PERCENTAGE;} {num}pt/{notnm} {BEGIN(0); return LENGTH;} {num}mm/{notnm} {BEGIN(0); return LENGTH;} {num}cm/{notnm} {BEGIN(0); return LENGTH;} {num}pc/{notnm} {BEGIN(0); return LENGTH;} {num}in/{notnm} {BEGIN(0); return LENGTH;} {num}px/{notnm} {BEGIN(0); return LENGTH;} {num}em/{notnm} {BEGIN(0); return EMS;} {num}ex/{notnm} {BEGIN(0); return EXS;} <AFTER_IDENT>":"link {return LINK_PSCLASS_AFTER_IDENT;} <AFTER_IDENT>":"visited {return VISITED_PSCLASS_AFTER_IDENT;} <AFTER_IDENT>":"active {return ACTIVE_PSCLASS_AFTER_IDENT;} <AFTER_IDENT>":"first-line {return FIRST_LINE_AFTER_IDENT;} <AFTER_IDENT>":"first-letter {return FIRST_LETTER_AFTER_IDENT;} <AFTER_IDENT>"#"{name} {return HASH_AFTER_IDENT;} <AFTER_IDENT>"."{name} {return CLASS_AFTER_IDENT;} ":"link {BEGIN(AFTER_IDENT); return LINK_PSCLASS;} ":"visited {BEGIN(AFTER_IDENT); return VISITED_PSCLASS;} ":"active {BEGIN(AFTER_IDENT); return ACTIVE_PSCLASS;} ":"first-line {BEGIN(AFTER_IDENT); return FIRST_LINE;} ":"first-letter {BEGIN(AFTER_IDENT); return FIRST_LETTER;} "#"{name} {BEGIN(AFTER_IDENT); return HASH;} "."{name} {BEGIN(AFTER_IDENT); return CLASS;} url\({w}{string}{w}\) | url\({w}([^ \n\'\")]|\\\ |\\\'|\\\"|\\\))+{w}\) {BEGIN(0); return URL;} rgb\({w}{num}%?{w}\,{w}{num}%?{w}\,{w}{num}%?{w}\) {BEGIN(0); return RGB;} [-/+{};,#:] {BEGIN(0); return *yytext;} [ \t]+ {BEGIN(0); /* ignore whitespace */} \n {BEGIN(0); /* ignore whitespace */} \<\!\-\- {BEGIN(0); return CDO;} \-\-\> {BEGIN(0); return CDC;} . {fprintf(stderr, "%d: Illegal character (%d)\n", lineno, *yytext);}
(This appendix is informative, not normative)
HTML documents may contain any of the about 30,000 different characters defined by Unicode. Many documents only need a few hundred. Many fonts also only contain just a few hundred glyphs. In combination with section 5.2, this appendix explains how the characters in the document and the glyphs in a font are matched.
The content of an HTML document is a sequence of characters and markup. To send it "over the wire", it is encoded as a sequence of bytes, using one of several possible encodings. The HTML document has to be decoded to find the characters. For example, in Western Europe it is customary to use the byte 224 for an a-with-grave-accent (à), but in Hebrew, it is more common to use 224 for an Aleph. In Japanese, the meaning of a byte usually depends on the bytes that preceded it. In some encodings, one character is encoded as two (or more) bytes.
The UA knows how to decode the bytes by looking at the "charset" parameter in the HTTP header. Typical encodings (charset values) are "ASCII" (for English), "ISO-8859-1" (for Western Europe), "ISO-8859-8" (for Hebrew), "Shift-JIS" (for Japanese).
HTML [2][4], allows some 30,000 different characters, namely those defined by Unicode. Not many documents will use that many different characters, and choosing the right encoding will usually ensure that the document only needs one byte per character. Occasional characters outside the encoded range can still be entered as numerical character references: 'Π' will always mean the Greek uppercase Pi, no matter what encoding was used. Note that this entails that UAs have to be prepared for any Unicode character, even if they only handle a few encodings.
A font doesn't contain characters, it contains pictures of characters, known as glyphs. The glyphs, in the form of outlines or bitmaps, constitute a particular representation of a character. Either explicitly or implicitly, each font has a table associated with it, the font encoding table, that tells for each glyph what character it is a representation for. In Type 1 fonts, the table is referred to as an encoding vector.
In fact, many fonts contain several glyphs for the same character. Which of those glyphs should be used depends either on the rules of the language, or on the preference of the designer.
In Arabic, for example, all letters have four different shapes, depending on whether the letter is used at the start of a word, in the middle, at the end, or in isolation. It is the same character in all cases, and thus there is only one character in the HTML document, but when printed, it looks differently each time.
There are also fonts that leave it to the graphic designer to choose from among various alternative shapes provided. Unfortunately, CSS1 doesn't yet provide the means to select those alternatives. Currently, it is always the default shape that is chosen from such fonts.
To deal with the problem that a single font may not be enough to display all the characters in a document, or even a single element, CSS1 allows the use of font sets.
A font set in CSS1 is a list of fonts, all of the same style and size, that are tried in sequence to see if they contain a glyph for a certain character. An element that contains English text mixed with mathematical symbols may need a font set of two fonts, one containing letters and digits, the other containing mathematical symbols. See section 5.2 for a detailed description of the selection mechanism for font sets.
Here is an example of a font set suitable for a text that is expected to contain text with Latin characters, Japanese characters, and mathematical symbols:
BODY { font-family: Baskerville, Mincho, Symbol, serif }
The characters available in the Baskerville font (a font with only Latin characters) will be taken from that font, Japanese will be taken from Mincho, and the mathematical symbols will come from Symbol. Any other characters will (hopefully) come from the generic font family 'serif'. The 'serif' font family will also be used if one or more of the other fonts is unavailable.
(This appendix is informative, not normative)
See the Gamma Tutorial in the PNG specification [12] if you aren't already familiar with gamma issues.
In the computation, UAs displaying on a CRT may assume an ideal CRT and ignore any effects on apparent gamma caused by dithering. That means the minimal handling they need to do on current platforms is:
"Applying gamma" means that each of the three R, G and B must be converted to R'=Rgamma, G'=Ggamma, B'=Bgamma, before handing to the OS.
This may rapidly be done by building a 256-element lookup table once per browser invocation thus:
for i := 0 to 255 do raw := i / 255; corr := pow (raw, gamma); table[i] := trunc (0.5 + corr * 255.0) end
which then avoids any need to do transcendental math per color attribute, far less per pixel.
(This appendix is informative, not normative)
The goal of the work on CSS1 has been to create a simple style sheet mechanism for HTML documents. The current specification is a balance between the simplicity needed to realize style sheets on the web, and pressure from authors for richer visual control. CSS1 offers:
<H1>H<FONT SIZE=-1>EADLINE</FONT></H1>
with the style sheet:
H1 { font-style: small-caps } <H1>Headline</H1>
CSS1 does not offer:
We expect to see extensions of CSS in several directions:
We do not expect CSS to evolve into:
(This appendix is informative, not normative)
This document is a revised version of the CSS1 Recommendation which was first published 17 December 1996 and the list below describes all changes. By selecting the alternate style sheet "errata", all changes will appear highlighted.
We would like to thank Komachi Yushi, Steve Byrne, Liam Quinn, Kazuteru Okahashi, Susan Lesch, and Tantek Çelik for their help in preparing this revised edition.
As as result, old UAs will ignore the 'STYLE' element, but its content will be treated as part of the document body, and rendered as such.
has been changed to:
As a result, old UAs will ignore the 'STYLE' element, but its content will be treated as part of the document body, and rendered as such.
The second selector matches matches all 'H1' elements that have an ancestor of class 'reddish'.
has been changed to:
The second selector matches all 'H1' elements that have an ancestor of class 'reddish'.
E.g., a style sheet can legally specify that the 'font-size' of an 'active' link should be larger that a 'visited' link, but the UA is not required to dynamically reformat the document when the reader selects the 'visited' link.
has been changed to:
E.g., a style sheet can legally specify that the 'font-size' of an 'active' link should be larger than a 'visited' link, but the UA is not required to dynamically reformat the document when the reader selects the 'visited' link.
"If more than one of the three is 'auto', and one of them is 'width', than the others..."
has been changed to:
"If more than one of the three is 'auto', and one of them is 'width', then the others..."
The margin properties properties set the margin of an element.
has been changed to:
The margin properties set the margin of an element.
font-style: small-caps
)
has been replaced by a valid one.
CSS1 assumes a simple box-oriented formatting model where each element results in one or more rectangular boxes.
has been replaced with:
CSS1 assumes a simple box-oriented formatting model where each formatted element results in one or more rectangular boxes.
The top is the top of the object including any padding, border and margin; it is only defined for inline and floating elements, not for non-floating block-level elements.
the word "object" has been replaced with "element" to use consistent Terminologie.
Note that the margin of the 'P' elements enclose the floating 'IMG' element.
has therefore been corrected to:
Note that the margin of the 'P' element enclose the floating 'IMG' element.
The 'margin' property sets the border for all four sides while the other margin properties only set their respective side.
has been corrected to:
The 'margin' property sets the margin for all four sides while the other margin properties only set their respective side.
"Applying gamma" means that each of the three R, G and B must be converted to R'=Rgamma, G'=Ggamma, G'=Bgamma, before handing to the OS.
has been changed to:
"Applying gamma" means that each of the three R, G and B must be converted to R'=Rgamma, G'=Ggamma, B'=Bgamma, before handing to the OS.