Example Web Page

18. XHTML Style Sheet Module

The Style Sheet Module defines an element to be used when declaring internal style sheets. The element and attributes defined by this module are:

Elements Attributes Minimal Content Model
style Common, media ( MediaDesc ) PCDATA

When this module is used, it adds the style element to the content model of the head element of the Structure Module.

18.1. The style element

The Common collection A collection of other attribute collections, including: Core, Events, I18N, Bi-directional, Edit, Embedding, Map, and Hypertext media = MediaDesc The value of this attribute specifies the type of media for which the element is intended.

The style element allows an author to put style sheet rules in the head of the document. XHTML permits any number of style elements in the head section of a document.

User agents that don’t support style sheets, or don’t support the specific style sheet language used by a style element, must hide the contents of the style element. It is an error to render the content as part of the document’s text.

The syntax of style data depends on the style sheet language.

Rules for style rule precedences and inheritance depend on the style sheet language.

18.1.1. External style sheets

Authors may separate style sheets from XHTML documents. This offers several benefits:

  • Authors and web site managers may share style sheets across a number of documents (and sites).
  • Authors may change the style sheet without requiring modifications to the document.
  • User agents may load style sheets selectively (based on media descriptors).
Читайте также:  Python exe файл py2exe

18.1.2. Preferred and alternate style sheets

XHTML allows authors to associate any number of external style sheets with a document. The style sheet language defines how multiple external style sheets interact (for example, the CSS «cascade» rules).

Authors may specify a number of mutually exclusive style sheets called style sheets. Users may select their favorite among these depending on their preferences. For instance, an author may specify one style sheet designed for small screens and another for users with weak vision (e.g., large fonts). User agents should allow users to select from alternate style sheets.

The author may specify that one of the alternates is a style sheet. User agents should apply the author’s preferred style sheet unless the user has selected a different alternate.

Authors may group several alternate style sheets (including the author’s preferred style sheets) under a single . When a user selects a named style, the user agent must apply all style sheets with that name. User agents must not apply alternate style sheets with a different style name. The section on specifying external style sheets explains how to name a group of style sheets.

User agents must respect media descriptors when applying any style sheet.

User agents should also allow users to disable the author’s style sheets entirely, in which case the user agent must not apply any persistent or alternate style sheets.

18.1.3. Specifying external style sheets

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

  • Set the value of href to the location of the style sheet file. The value of href is a URI .
  • Set the value of the type attribute to indicate the language of the linked (style sheet) resource. This allows the user agent to avoid downloading a style sheet for an unsupported style sheet language.
  • Specify that the style sheet is persistent, preferred, or alternate:
    • To make a style sheet persistent, set the rel attribute to «stylesheet» and don’t set the title attribute.
    • To make a style sheet preferred, set the rel attribute to «stylesheet» and name the style sheet with the title attribute.
    • To specify an alternate style sheet, set the rel attribute to «alternate stylesheet» and name the style sheet with the title attribute.

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

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

    Setting the title attribute makes this the author’s preferred style sheet:

    Adding the keyword «alternate» to the rel attribute makes it an alternate style sheet:

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

    If two or more link elements specify a preferred style sheet, the first one takes precedence.

    Источник

    Cascading Style Sheets/Applying CSS to HTML and XHTML

    CSS can be applied to HTML or XHTML using three methods: linked, embedded, and inline. In the linked method, the CSS is stored in a separate file, instead of directly in the HTML page. In the embedded method, CSS is stored as part of the HTML page, in the header section. In the inline method, CSS is stored directly in the style attributes of the HTML tags, as

    Bold Font

    .

    The neatest method is probably the linked one, but the other ones are convenient and quick in the phases of prototyping a web page. The embedded and inline methods do not require having a separate file. The inline method saves you the trouble of considering what CSS classes your document should have. For a larger site, in which many web pages share the same styling, and in which the styling should be customizable by the user, the linked method is the only viable option.

    The methods are treated in detail in the following sections.

    Linking [ edit | edit source ]

    With linked CSS, CSS rules are stored in a separate file. To refer to that file from the HTML page, add the link element (and its closing element within XHTML) to the head element, as shown in the following example, which assumes that the stylesheet is stored in the file named «style.css».

    The link element in the example has three attributes. The first, rel , tells the browser the type of the target of the link. The second, type , tells the browser what type of stylesheet it is. And the third, href , tells the browser under which URL to find the stylesheet. In the example, the URL is relative, but it can also be absolute.

    The «style.css» with a single rule contains only the following text:

    This tells the browser that the text in the paragraph ( p ) element should be rendered as bold.

    Text that will be formatted.

    The source code for the complete HTML document is thus as follows:

         

    Text that will be formatted.

    Embedding [ edit | edit source ]

    Dynamically generated webpages may need to use embedded CSS, but this should be kept to a minimum. Even in dynamic pages, any CSS that is common to multiple pages should generally be moved to a linked stylesheet.

    Embedded CSS is CSS that is located in the header of the HTML document that requires styling. For example we would like the text in this HTML document to appear bold.

          

    Text that will be formatted.

    The CSS may be placed in the document’s header section:

    The CSS is contained in a style element. Setting the element’s type attribute to text/css tells the browser that the enclosed sheetstyle is written in CSS and should be used to format the page. If the attribute type is missing or set to an unrecognized value, the CSS will not be applied to the page.

    The bit of CSS in this example tells the browser to make all the text found in any paragraph ( p ) elements bold. The text on the page would look like this:

    Text that will be formatted.

    Here is the complete document including the CSS.

        p  

    Text that will be formatted.

    Remember, you should use linked stylesheets in preference to embedded stylesheets whenever possible. That will allow easy replacement of the general style information without having to keep track of styles within the various HTML files.

    Inlining [ edit | edit source ]

    Inline CSS is specified directly in the opening tag of the element you want it to apply to. It is entered into the style attribute within HTML or XHTML 1.1.

    As mentioned, you should in general prefer linked CSS to embedded CSS, and both are preferred over inline CSS.

    Источник

    Интеграция CSS в xHTML-документ

    CSS (Cascading Style Sheets — каскадные таблицы стилей) – способ видоизменения частей документов, созданных при помощи языка разметки.

    CSS может быть внедрена непосредственно в документ. Это делается с помощью открывающего тега с параметром type=text/css. После чего указываются компоненты документа, к которым будут применены стили. Функции к параметрам начинаются с фигурной скобки и заканчиваются обратной фигурной скобкой >. Между функцией и её значением ставится двоеточие : . Функция закрывается точкой с запятой ; после описания её значения. Затем устанавливается закрывающий тег , после которого идёт уже редактирование документа.

    Пример внедрения css в документ:


    font

    family : Times New Roman ;
    size : 14pt ;
    >

    Так же CSS может работать в документе, являясь отдельным документом – списком стилей для отдельных компонентов. Документ будет обладать расширением *.css, а в сам документ разметки CSS будет внедрён благодаря тегу вначале документа между тегами , т.е.

    Здесь параметр:
    — href=’/папка с css/документ.css’ указывает путь к файлу CSS, при помощи которого будет применено видоизменение данного документа.

    На практике бывают такие моменты, когда необходимо, чтобы из всего контента страницы стиль был применен к какому-либо одному элементу. Так, например, из всего текста необходимо выделить некую фразу, другими словами придать ей стиль. Можно, конечно, присвоить для такого элемента отдельный стиль и прописать его отдельным контейнером в CSS-документе. Но согласитесь, по каждому отдельному элементу создавать отдельный класс — это не удобно. А что делать, если у вас таких фраз, которые надо выделить по особому — будет на каждой странице? Не запутаетесь? Есть выход. Прямо в коде страницы приписываем стиль именно к данной фразе. Делается это следующим образом:

    Следите за синтаксисом при подобном присвоении стиля — в противном случае стиль может быть либо не применён к конкретному элементу, или и вовсе — изменить дизайн всей страницы в целом.

    Источник

Оцените статью