Movatterモバイル変換


[0]ホーム

URL:


 previous  next  contents  elements  attributes  index

14StyleSheets

Contents

  1. Introduction to style sheets
  2. Adding style to HTML
    1. Setting the default style sheetlanguage
    2. Inline style information
    3. Header style information: theSTYLE element
    4. Media types
  3. External style sheets
    1. Preferred and alternate stylesheets
    2. Specifying external stylesheets
  4. Cascading style sheets
    1. Media-dependent cascades
    2. Inheritance and cascading
  5. Hiding style data from useragents
  6. Linking to style sheets with HTTPheaders

14.1Introduction to stylesheets

Style sheets represent a major breakthrough for Web page designers,expanding their ability to improve the appearance of their pages. In thescientific environments in which the Web was conceived, people are moreconcerned with the content of their documents than the presentation. As peoplefrom wider walks of life discovered the Web, the limitations of HTML became asource of continuing frustration and authors were forced to sidestep HTML'sstylistic limitations. While the intentions have been good -- to improve thepresentation of Web pages -- the techniques for doing so have had unfortunateside effects. These techniques work for some of the people, some of the time,but not for all of the people, all of the time. They include:

These techniques considerably increase the complexity of Web pages, offerlimited flexibility, suffer from interoperability problems, and createhardships for people with disabilities.

Style sheets solve these problems at the same time they supersede thelimited range of presentation mechanisms in HTML. Style sheets make it easy tospecify the amount of white space between text lines, the amount lines areindented, the colors used for the text and the backgrounds, the font size andstyle, and a host of other details.

For example, the following short CSS style sheet (stored in the file"special.css"), sets the text color of a paragraph to green and surrounds itwith a solid red border:

P.special {color : green;border: solid red;}

Authors may link this style sheet to their source HTML document with theLINK element:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"   "http://www.w3.org/TR/html4/strict.dtd"><HTML>  <HEAD>    <LINK href="special.css" rel="stylesheet" type="text/css">  </HEAD>  <BODY>    <P>This paragraph should have special green text.  </BODY></HTML>

HTML 4 provides support for the following style sheet features:

Flexible placement of style information
Placing style sheets in separate files makes them easy to reuse. Sometimesit's useful to include rendering instructions within the document to which theyapply, either grouped at the start of the document, or in attributes of theelements throughout the body of the document. To make it easier to manage styleon a site basis, this specification describes how to use HTTP headers to setthe style sheets to be applied to a document.
Independence from specific style sheet languages
This specification doesn't tie HTML to any particular style sheet language.This allows for a range of such languages to be used, for instance simple onesfor the majority of users and much more complex ones for the minority of userswith highly specialized needs. The examples included below all use the CSS(Cascading Style Sheets) language[CSS1], but other stylesheet languages would be possible.
Cascading
This is the capability provided by some style sheet languages such as CSSto allow style information from several sources to be blended together. Thesecould be, for instance, corporate style guidelines, styles common to a group ofdocuments, and styles specific to a single document. By storing theseseparately, style sheets can be reused, simplifying authoring and making moreeffective use of network caching. The cascade defines an ordered sequence ofstyle sheets where rules in later sheets have greater precedence than earlierones. Not all style sheet languages support cascading.
Media dependencies
HTML allows authors to specify documents in a media-independent way. Thisallows users to access Web pages using a wide variety of devices and media,e.g., graphical displays for computers running Windows, Macintosh OS, and X11,devices for television sets, specially adapted phones and PDA-based portabledevices, speech-based browsers, and braille-based tactile devices.

Style sheets, by contrast, apply to specific media or media groups. A stylesheet intended for screen use may be applicable when printing, but is of littleuse for speech-based browsers. This specification allows you to define thebroad categories of media a given style sheet is applicable to. This allowsuser agents to avoid retrieving inappropriate style sheets. Style sheetlanguages may include features for describing media dependencies within thesame style sheet.

Alternate styles
Authors may wish to offer readers several ways to view a document. Forinstance, a style sheet for rendering compact documents with small fonts, orone that specifies larger fonts for increased legibility. This specificationallows authors to specify a preferred style sheet as well as alternates thattarget specific users or media. User agents should give users the opportunityto select from among alternate style sheets or to switch off style sheetsaltogether.
Performance concerns
Some people have voiced concerns over performance issues for style sheets.For instance, retrieving an external style sheet may delay the fullpresentation for the user. A similar situation arises if the document headincludes a lengthy set of style rules.

The current proposal addresses these issues by allowing authors to includerendering instructions within each HTML element. The rendering information isthen always available by the time the user agent wants to render eachelement.

In many cases, authors will take advantage of a common style sheet for agroup of documents. In this case, distributing style rules throughout thedocument will actually lead to worse performance than using a linked stylesheet, since for most documents, the style sheet will already be present in thelocal cache. The public availability of good style sheets will encourage thiseffect.

14.2 Adding style to HTML

Note. The sample default style sheet for HTML 4 that isincluded in[CSS2] expresses generally accepted default style informationfor each element. Authors and implementors alike might find this a usefulresource.

HTML documents may contain style sheet rules directly in them or they mayimport style sheets.

Any style sheet language may be used with HTML. A simple style sheetlanguage may suffice for the needs of most users, but other languages may bemore suited to highly specialized needs. This specification uses the stylelanguage "Cascading Style Sheets" ([CSS1]), abbreviated CSS,for examples.

Thesyntax of style data depends onthe style sheet language.

14.2.1Setting the default style sheet language

Authors must specify the style sheet language of style informationassociated with an HTML document.

Authors should use theMETA element to set the default stylesheet language for a document. For example, to set the default to CSS, authorsshould put the following declaration in theHEAD of their documents:

<META http-equiv="Content-Style-Type" content="text/css">

The default style sheet language may also be set with HTTP headers. TheaboveMETA declaration is equivalent to the HTTP header:

Content-Style-Type: text/css

User agents should determine the default style sheet language for a documentaccording to the following steps (highest to lowest priority):

  1. If anyMETA declarations specify the "Content-Style-Type",the last one in the character stream determines the default style sheetlanguage.
  2. Otherwise, if any HTTP headers specify the "Content-Style-Type", the lastone in the character stream determines the default style sheet language.
  3. Otherwise, the default style sheet language is "text/css".

Documents that include elements that set thestyleattribute but which don't define a default style sheet language are incorrect.Authoring tools shouldgenerate default style sheet language information (typically aMETA declaration) so that user agents do not have to rely on adefault of "text/css".

14.2.2Inline styleinformation

Attribute definitions

style =style[CN]
This attribute specifies style information for the current element.

Thesyntax of the value of thestyle attribute is determined by thedefault style sheet language. For example, for [[CSS2]]inline style, use the declaration block syntax described in section 4.1.8(without curly brace delimiters).

This CSS example sets color and font size information for the text in aspecific paragraph.

<P>Aren't style sheets wonderful?

In CSS, property declarations have the form "name : value" and are separatedby a semi-colon.

To specify style information for more than one element, authors should usetheSTYLE element. For optimal flexibility, authorsshould define styles in external style sheets.

14.2.3Header styleinformation: theSTYLEelement

<!ELEMENTSTYLE - -%StyleSheet        -- style info --><!ATTLIST STYLE%i18n;                               --lang,dir, for use with title --type%ContentType;  #REQUIRED -- content type of style language --media%MediaDesc;    #IMPLIED  -- designed for use with these media --title%Text;         #IMPLIED  -- advisory title --  >

Start tag:required, End tag:required

Attribute definitions

type =content-type[CI]
This attribute specifies the style sheet language of the element's contentsand overrides the default style sheet language. The style sheet language isspecified as a content type (e.g., "text/css"). Authors must supply a value forthis attribute; there is no default value for this attribute.
media =media-descriptors[CI]
This attribute specifies the intended destination medium for styleinformation. It may be a single media descriptor or a comma-separated list. Thedefault value for this attribute is "screen".

Attributes defined elsewhere

TheSTYLE element allows authors to put style sheet rules in thehead of the document. HTML permits any number ofSTYLE elements in theHEAD section of a document.

User agents that don't support style sheets, or don't support the specificstyle sheet language used by aSTYLE element, must hide the contents of theSTYLE element.It is an error to renderthe content as part of the document's text. Some style sheet languages supportsyntax forhiding the content from non-conforming useragents.

Thesyntax of style data depends onthe style sheet language.

Some style sheet implementations may allow a wider variety of rules in theSTYLE element than in thestyle attribute. For example, with CSS,rules may be declared within aSTYLE element for:

Rules for style rule precedences and inheritance depend on the style sheetlanguage.

The following CSSSTYLE declaration puts a border around everyH1 element in the document and centers it on the page.

<HEAD> <STYLE type="text/css">   H1 {border-width: 1; border: solid; text-align: center} </STYLE></HEAD>

To specify that this style information should only apply toH1 elements of a specific class, we modify it as follows:

<HEAD> <STYLE type="text/css">   H1.myclass {border-width: 1; border: solid; text-align: center} </STYLE></HEAD><BODY> <H1> This H1 is affected by our style </H1> <H1> This one is not affected by our style </H1></BODY>

Finally, to limit the scope of the style information to a single instance ofH1, set theid attribute:

<HEAD> <STYLE type="text/css">   #myid {border-width: 1; border: solid; text-align: center} </STYLE></HEAD><BODY> <H1> This H1 is not affected </H1> <H1> This H1 is affected by style </H1> <H1> This H1 is not affected </H1></BODY>

Although style information may be set foralmost every HTML element, two elements,DIV andSPAN, are particularly useful in that they donot impose any presentation semantics (besidesblock-level vs. inline). When combinedwith style sheets, these elements allow users to extend HTML indefinitely,particularly when used with theclass andid attributes.

In the following example, we use theSPAN element to set the font style of the first few words of aparagraph to small caps.

<HEAD> <STYLE type="text/css">  SPAN.sc-ex { font-variant: small-caps } </STYLE></HEAD><BODY>  <P><SPAN>The first</SPAN> few words of  this paragraph are in small-caps.</BODY>

In the following example, we useDIV and theclass attribute to set the text justification for a series ofparagraphs that make up the abstract section of a scientific article. Thisstyle information could be reused for other abstract sections by setting theclass attribute elsewhere in the document.

<HEAD> <STYLE type="text/css">   DIV.Abstract { text-align: justify } </STYLE></HEAD><BODY> <DIV>   <P>The Chieftain product range is our market winner for     the coming year. This report sets out how to position     Chieftain against competing products.   <P>Chieftain replaces the Commander range, which will     remain on the price list until further notice. </DIV></BODY>

14.2.4Mediatypes

HTML allows authors to design documents that take advantage of thecharacteristics of the media where the document is to be rendered (e.g.,graphical displays, television screens, handheld devices, speech-basedbrowsers, braille-based tactile devices, etc.). By specifying themediaattribute, authors allow user agents to load and apply style sheetsselectively. Please consult the list of recognizedmedia descriptors.

The following sample declarations apply toH1 elements. When projected in a business meeting, all instanceswill be blue. When printed, all instances will be centered.

<HEAD> <STYLE type="text/css" media="projection">    H1 { color: blue} </STYLE> <STYLE type="text/css" media="print">   H1 { text-align: center } </STYLE>

This example adds sound effects to anchors for use in speech output:

 <STYLE type="text/css" media="aural">   A { cue-before: uri(bell.aiff); cue-after: uri(dong.wav)} </STYLE></HEAD>

Media control is particularly interesting when applied to external stylesheets since user agents can save time by retrieving from the network onlythose style sheets that apply to the current device. For instance, speech-basedbrowsers can avoid downloading style sheets designed for visual rendering. Seethe section onmedia-dependent cascades for moreinformation.

14.3External style sheets

Authors may separate style sheets from HTML documents. This offers severalbenefits:

14.3.1 Preferred and alternate style sheets

HTML allows authors to associate any number of external style sheets with adocument. The style sheet language defines how multiple external style sheetsinteract (for example, the CSS "cascade" rules).

Authors may specify a number of mutuallyexclusive style sheets calledalternate style sheets.Users may select their favorite among these depending on their preferences. Forinstance, an author may specify one style sheet designed for small screens andanother for users with weak vision (e.g., large fonts). User agents shouldallow users to select from alternate style sheets.

The author may specify that one of thealternates is apreferred style sheet. User agents shouldapply the author's preferred style sheet unless the user has selected adifferent alternate.

Authors may group several alternate style sheets (including the author'spreferred style sheets) under a singlestyle name. When a userselects a named style, the user agent must apply all style sheets with thatname. User agents must not apply alternate style sheets with a different stylename. The section onspecifying external stylesheets explains how to name a group of style sheets.

Authors may also specifypersistent style sheets that user agents must apply in addition to anyalternate style sheet.

User agents must respectmedia descriptors when applying any style sheet.

User agents should also allow users to disable the author's style sheetsentirely, in which case the user agent must not apply any persistent oralternate style sheets.

14.3.2Specifying external style sheets

Authors specify external style sheets with the following attributes of theLINK element:

User agents should provide a means for users to view and pick from the listof alternate styles. The value of thetitle attribute is recommended as the name of each choice.

In this example, we first specify a persistent style sheet located in thefilemystyle.css:

<LINK href="mystyle.css" rel="stylesheet" type="text/css">

Setting thetitle attribute makes this the author's preferredstyle sheet:

 <LINK href="mystyle.css" title="compact" rel="stylesheet" type="text/css">

Adding the keyword "alternate" to therel attribute makes it an alternate style sheet:

<LINK href="mystyle.css" title="Medium" rel="alternate stylesheet" type="text/css">

For more information on external style sheets, please consult the section onlinks and external stylesheets.

Authors may also use theMETA element to set the document's preferred stylesheet. For example, to set the preferred style sheet to "compact" (seethe preceding example), authors may include the following line in theHEAD:

<META http-equiv="Default-Style" content="compact">

The preferred style sheet may also be specified with HTTP headers. The aboveMETA declaration is equivalent to the HTTP header:

Default-Style: "compact"

If two or moreMETA declarations or HTTP headers specify thepreferred style sheet, the last one takes precedence. HTTP headers areconsidered to occur earlier than the documentHEAD for this purpose.

If two or moreLINK elements specify a preferred style sheet, thefirst one takes precedence.

Preferred style sheets specified withMETA or HTTP headers have precedence over those specified with theLINK element.

14.4Cascadingstyle sheets

Cascading style sheet languages such as CSS allow styleinformation from several sources to be blended together. However, not all stylesheet languages support cascading. To define a cascade, authors specify asequence ofLINK and/orSTYLE elements. The style informationis cascaded in the order the elements appear in theHEAD.

Note. This specification does not specify how stylesheets from different style languages cascade. Authors should avoid mixingstyle sheet languages.

In the following example, we specify two alternate style sheets named"compact". If the user selects the "compact" style, the user agent must applyboth external style sheets, as well as the persistent "common.css" style sheet.If the user selects the "big print" style, only the alternate style sheet"bigprint.css" and the persistent "common.css" will be applied.

<LINK rel="alternate stylesheet" title="compact" href="small-base.css" type="text/css"><LINK rel="alternate stylesheet" title="compact" href="small-extras.css" type="text/css"><LINK rel="alternate stylesheet" title="big print" href="bigprint.css" type="text/css"><LINK rel="stylesheet" href="common.css" type="text/css">

Here is a cascade example that involves both theLINK andSTYLE elements.

<LINK rel="stylesheet" href="corporate.css" type="text/css"><LINK rel="stylesheet" href="techreport.css" type="text/css"><STYLE type="text/css">    p.special { color: rgb(230, 100, 180) }</STYLE>

14.4.1Media-dependent cascades

A cascade may include style sheets applicable to different media. BothLINK andSTYLE may be used with themediaattribute. The user agent is then responsible for filtering out those stylesheets that do not apply to the current medium.

In the following example, we define a cascade where the "corporate" stylesheet is provided in several versions: one suited to printing, one for screenuse and one for speech-based browsers (useful, say, when reading email in thecar). The "techreport" stylesheet applies to all media. The color rule definedby theSTYLE element is used for print and screen but not for auralrendering.

<LINK rel="stylesheet" media="aural" href="corporate-aural.css" type="text/css"><LINK rel="stylesheet" media="screen" href="corporate-screen.css" type="text/css"><LINK rel="stylesheet" media="print" href="corporate-print.css" type="text/css"><LINK rel="stylesheet" href="techreport.css" type="text/css"><STYLE media="screen, print" type="text/css">    p.special { color: rgb(230, 100, 180) }</STYLE>

14.4.2 Inheritance and cascading

When the user agent wants to render a document, it needs to find values forstyle properties, e.g. the font family, font style, size, line height, textcolor and so on. The exact mechanism depends on the style sheet language, butthe following description is generally applicable:

The cascading mechanism is used when a number of style rules all applydirectly to an element. The mechanism allows the user agent to sort the rulesby specificity, to determine which rule to apply. If no rule can be found, thenext step depends on whether the style property can be inherited or not. Notall properties can be inherited. For these properties the style sheet languageprovides default values for use when there are no explicit rules for aparticular element.

If the property can be inherited, the user agent examines the immediatelyenclosing element to see if a rule applies to that. This process continuesuntil an applicable rule is found. This mechanism allows style sheets to bespecified compactly. For instance, authors may specify the font family for allelements within theBODY by a single rule that applies to theBODY element.

14.5Hiding style data from user agents

Some style sheet languages support syntax intended to allow authors to hidethe content ofSTYLE elements from non-conforming user agents.

This example illustrates for CSS how to comment out the content ofSTYLEelements to ensure that older, non-conforming user agents will not render themas text.

<STYLE type="text/css"><!--   H1 { color: red }   P  { color: blue}   --></STYLE>

14.6Linking to style sheets withHTTP headers

This section only applies to user agents conforming to versions of HTTPthat define a Link header field. Note that HTTP 1.1 as defined by[RFC2616] does not include a Link header field (refer to section19.6.3).

Web server managers may find it convenient to configure a server so that astyle sheet will be applied to a group of pages. The HTTPLink headerhas the same effect as aLINK element with the same attributesand values. MultipleLink headers correspond to multipleLINK elements occurring in the same order. For instance,

Link: <http://www.acme.com/corporate.css>; REL=stylesheet

corresponds to:

<LINK rel="stylesheet" href="http://www.acme.com/corporate.css">

It is possible to specify several alternate styles using multipleLink headers, and then use therel attribute to determine thedefault style.

In the following example, "compact" is applied by default since it omits the"alternate" keyword for therel attribute.

Link: <compact.css>; rel="stylesheet"; title="compact"Link: <bigprint.css>; rel="alternate stylesheet"; title="big print"

This should also work when HTML documents are sent by email. Some emailagents can alter the ordering of[RFC822] headers. Toprotect against this affecting the cascading order for style sheets specifiedbyLink headers, authors can use header concatenation to merge severalinstances of the same header field. The quote marks are only needed when theattribute values include whitespace. Use SGML entities to reference charactersthat are otherwise not permitted within HTTP or email headers, or that arelikely to be affected by transit through gateways.

LINK andMETA elements implied by HTTP headers aredefined as occurring before any explicitLINK andMETA elements in the document'sHEAD.


previous  next  contents elements  attributes  index

[8]ページ先頭

©2009-2025 Movatter.jp