Cascading Style Sheets and dynamic HTML

41 403 0
Cascading Style Sheets and dynamic HTML

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

to specify how the document should look. Instead, you use CSS to define a style sheet that specifies how the structured elements of your document should be displayed. For example, you can use CSS to specify that the level-one headings defined by <h1> tags should be displayed in bold, sans-serif, centered, uppercase, 24-point letters. , also the aural is a technology intende concerned with the isplay of HT client-side JavaScript programmers because the d ts of a do enable a variety of visual ef HTML (DHTML). [2] [1] And, in the CSS2 standard presentation. CSS d for use by graphic designers or anyone precise visual d ML documents. It is of interest to ocument object model allows the styles that are applied to the cument to be scripted. Used together, CSS and JavaScript fects loosely referred to as Dynamic individual elemen effects also inv a qu hapter 19 [2] Many advanced DHTML olve the event-h ndling techni es we'll see in C . ity to script CSS sty ws you to dynamically change colors, fonts, and so e importantly, it allows you to set and change the position of elements and even and show elements. e DHTML techniques to create s where document content "slides in" from the right, for example, or d collapsin ontrol the amount of on that is displaye This chapter begins with an overview of CSS style sheets and the use of CSS styles to s ets with CSS Styles in CSS are specified as a semicolon-separated list of name/value attribute pairs, The CSS standard defines quite a few style attributes you can set. Table 18-1 The abil on. Mor les allo to hide This means that you can us animated transition an expanding an g outline list in which the user can c informati d. specify the position and visibility of document elements. It then explains how CSS style can be scripted using the API defined by the DOM Level 2 standard. Finally, it demonstrates the nonstandard, browser-specific APIs that can be used to achieve DHTML effects in Netscape 4 and Internet Explorer 4. 18.1 Styles and Style She where each name and value are separated by colons. For example, the following style specifies bold, blue, underlined text: font-weight: bold; color: blue; text-decoration: underline; lists all the attributes except for those used only in audio style sheets. You are not expected to SS, eyer (O'Reilly), or O'Reilly). Or read the s /REC-CSS2/ understand or be familiar with all these attributes, their values, or their meanings. As you become familiar with CSS and use it in your documents and scripts, however, you may find this table a convenient quick reference. For more complete documentation on C consult Cascading Style Sheets: The Definitive Guide, by Eric M Dynamic HTML: The Definitive Guide, by Danny Goodman ( pecification itself -- you can find it at http://www.w3c.org/TR . The second column of Table 18-1 shows the allowed values for each style attribute. It uses the grammar used by the CSS specification. Items in fixed-width font are keywords and should appear exactly as shown. Items in italics specify a data type such a string or a length. Note that the as e Values separated by a are alternatives; you must specify exactly one. Values separated [] are used for grouping values. An asterisk (*) specifies that the previous value or group may appear zero or more times, a es specify a number of repetitions. For example, { st be repeated twice, and {1,4} specifies that the previous item must appear at least once and no more than four times. (This repetition length type is a number followed by a units specification such as px (for pixels). See a CSS reference for details on the other types. Items that appear in italic fixed-width font represent the set of values allowed by some other CSS attribute. In addition to the values shown in the table, each style attribut may have the value "inherit", to specify that it should inherit the value from its parent. | by || are options; you must specify at least one, but you may specify more than one, and they can appear in any order. Square brackets plus sign (+) specifies that the previous value or group may appear one or more times, and a question mark (?) specifies that the previous item is optional and may appear zero or one time. Numbers within curly brac 2} specifies that the previous item mu syntax may seem familiar: it is the same one used by JavaScript regular expressions, discussed in Chapter 10.) Table 18-1. CSS style attributes and their values Name Values background r ||background-image ||background- repeat || background-attachment ||background- [background-colo position] background- attachment scroll | fixed background-color color | transparent background-image url( url ) | none background-position [ [percentage | length ]{1,2} | [ [top | center | bottom] || [left | center | right] ] ] background-repeat repeat | repeat-x | repeat-y | no-repeat border [ border-width ||border-style || color ] border-collapse collapse | separate border-color color{1,4} | transparent border-spacing length length? border-style [none | hidden | dotted | dashed | solid | double | groove | Table 18-1. CSS style attributes and their values Name Values ridge | inset | outset]{1,4} border-top border- right border-bottom border-left [ border-top-width ||border-top-style || color ] border-top-color border-right-color border-bottom-color color border-left-color border-top-style border-right-style border-bottom-style border-left-style none | hidden | dotted | dashed | solid | double | groove ridge | | inset | outset border-top-width border-right-width border-bottom-width medium thick border-left-width thin | | | length border-width [thin | medium | thick | length]{1,4} bottom length | percentage | auto caption-side top | bottom | left | right clear none | left | right | both clip [rect( [length | auto]{4} )] | auto color color content [ string | url( url ) | counter | attr(attribute-name) | open- quote | close-quote | no-open-quote | no-close-quote ]+ counter-increment [ identifier integer? ]+ | none counter-reset [ identifier integer? ]+ | none cursor [ [url( url ) ,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se- resize | sw-resize | s-resize | w-resize | text | wait help | ] ] direction ltr rtl | display inline | block | list-item | run-in | compact | marker | table | inline-table | table-row-group | table-header- group | table-footer-group | table-row | table-column- group | table-column | table-cell | table-caption | none Table 18-1. CSS style attributes and their values Name Values empty-cells show | hide float left | right | none font [ [ font-style || font-variant || font-weight ]? font- size [ / line-height ]? font-family ] | caption | icon | menu | message-box | small-caption | status-bar font-family [[ family-name | serif | sans-serif | monospace | cursive | fantasy],]+ font-size xx-small | x-small | small | medium | large | x-large | xx- large | smaller | larger | length | percentage font-size-adjust number | none font-stretch nsed | extra- condensed | condensed | semi-condensed | semi-expanded panded | extra-expanded | ultra-expanded normal | wider | narrower | ultra-conde | ex font-style normal | italic | oblique font-variant normal | small-caps font-weight | 600 | 700 | 800 | 900 normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 height length | percentage | auto left length | percentage | auto letter-spacing normal | length line-height normal | number | length | percentage list-style [ list-style-type || list-style-position || list- style-image ] list-style-image url( url ) | none list-style-position inside | outside list-style-type lower-roman | upper-roman | lower-greek | lower-alpha | | | | | disc | circle | square | decimal | decimal-leading-zero | upper-alpha upper-latin hebrew orgian | cjk-ideographic | hiragana | ragana-iroha | katakana-iroha | none lower-latin armenian | ge katakana | hi margin [length | percentage | auto]{1,4} Table 18-1. CSS style attributes and their values Name Values margin-topmargin- right margin-bottom length | percentage | auto margin-left marker-offset length | auto marks [ || ] | nonecrop cross max-height length | percentage | none max-width length | percentage | none min-height length | percentage min-width length | percentage orphans integer outline [ outline-color || outline-style || outline-width ] outline-color color | invert outline-style none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset outline-width thin | medium | thick | length overflow visible | hidden | scroll | auto padding [length | percentage]{1,4} padding-top padding-bottom padding- right eft length | percentage padding-l page identifier | auto page-break-after auto | always | avoid | left | right page-break-before auto | always | avoid | left | right page-break-inside avoid | auto position static | relative | absolute | fixed quotes [string string]+ | none right length | percentage | auto size length{1,2} | auto | portrait | landscape table-layout auto | fixed Table 18-1. CSS style attributes and their values Name es Valu text-align left | right | center | justify | string text-decoration none | [ underline || overline || line-through || blink ] text-indent length | percentage text-shadow none | [color || length length length? ,]* [color || length length length?] text-transform capitalize | uppercase | lowercase | none top length | percentage | auto unicode-bidi normal | embed | bidi-override vertical-align baseline | sub | super | top | text-top | middle | bottom | text-bottom | percentage | length visibility visible | hidden | collapse white- p space normal | pre | nowra widows integer width length | percentage | auto word-spacing normal | length z-index auto | integer The CS combin font-style, and font-weight attributes can all be set at once using a single font attribute: font: bold italic 24pt helvetica; In fact, S standard allows certain style attributes that are commonly used together to be ed using special shortcut attributes. For example, the font-family, font-size, some of the attributes listed in Table 18-1 are themselves shortcuts. The margin and pa borders attribut and sim dding attributes are shortcuts for attributes that specify margins, padding, and for each of the individual sides of an element. Thus, instead of using the margin e, you can use margin-left, margin-right, margin-top, and margin-bottom, ilarly for padding. 18.1.1 You ca way is margin <p style="margin-left: 1in; margin-right: 1in;"> One of the important goals of CSS is to separate document content and structure from document presentation. Specifying styles with the style attribute of individual HTML tags does not accomplish this (although it can be a useful technique for DHTML). To achieve the separation of structure from presentation, we use style sheets, which group all the style information into a single place. A CSS style sheet consists of a set of style rules. Each rule begins with a selector that specifies the document element or elements to which it applies, followed by a set of style attributes and their values within curly braces. The simplest kind of rule defines styles for one or more specific tag names. For example, the following rule sets the margins and background color for the <body> tag: r: #ffffff } The following rule specifies that text within <h1> and <h2> headings should be centered: h1, h2 { text-align: center; } In the previous example, note the use of a comma to separate the tag names to which the styles are to apply. If the comma is omitted, the selector specifies a contextual rule that applies only when one tag is nested within another. For example, the following rules Another kind of style sheet rule uses a different selector to specify a class of elements to t is defined by the class ttribute of the HTML tag. For example, the following rule specifies that any tag with the Applying Style Rules to Document Elements n apply style attributes to the elements of a document in a number of ways. One to use them in the style attribute of an HTML tag. For example, to set the s of an individual paragraph, you can use a tag like this: body { margin-left: 30px; margin-right: 15px; background-colo specify that <blockquote> tags are displayed in an italic font, but text inside an <i> tag inside a <blockquote> is displayed in plain, nonitalic text: blockquote { font-style: italic; } blockquote i { font-style: normal; } which its styles should be applied. The class of an elemen a attribute class="attention" should be displayed in bold: .attention { font-weight: bold; } Class selectors can be combined with tag name selectors. The following rule specifies that when a <p> tag has the class="attention" attribute, it should be displayed in red, in addition to being displayed in a bold font (as specified by the previous rule): id attribute. The following rule specifies that the element with an id attribute #p1 { visibility: hidden; } e value ble, causing the element to dynamically appear. le> tags within the <head> of the document, or you can store the k> nked also define inline styles for f rules for determining which rules from de take precedence over the other rules. Briefly, however, what you need to now is that the user style sheet overrides the default browser style sheet, author style sheets override the user style sheet, and inline styles override everything. The exception to this general rule is that user style attributes whose values include the !important p.attention { color: red; } Finally, style sheets can contain rules that apply only to individual elements that have a specified equal to "p1" should not be shown: We've seen the id attribute before: it is used with the DOM function getElementById( ) to return individual elements of a document. As you might imagine, this kind of element-specific style sheet rule is useful when we want to manipulate the style of an individual element. Given the previous rule, for example, a script might switch th of the visibility attribute from hidden to visi 18.1.2 Associating Style Sheets with Documents You can incorporate a style sheet into an HTML document by placing it between <style> and </sty style sheet in a file of its own and reference it from the HTML document using a <lin tag. You can also combine these two techniques by creating a document-specific style sheet between <style> tags that references or imports a document-independent style sheet using the special @import "at-rule." Consult a CSS reference for details on @import. 18.1.3 The Cascade Recall that the C in CSS stands for "cascading." This term indicates that the style rules that apply to any given element in a document can come from a cascade of different sources. Each web browser typically has its own default styles for all HTML elements and may allow the user to override these defaults with a user style sheet. The author of a document can define style sheets within <style> tags or in external files that are li in or imported into other style sheets. The author may individual elements with the HTML style attribute. The CSS specification includes a complete set o the casca k modifier override author styles. Within a style sheet, if more than one rule applies to an element, styles defined by the most specific rule override conflicting styles defined by less specific rules. Rules that specify an element id are the most specific. Rules that specify a class are next. Rules that specify only tag names are the least specific, but rules that specify multiple nested tag names are more specific than rules that specify only a single tag name. 18.1.4 Versions of CSS At the time of this writing, there are two versions of the CSS standard. CSS1 was adopted in December, 1996 and defines attributes for specifying colors, fonts, margins, borders, and other basic styles. Netscape 4 and Internet Explorer 4 both implement at least partial support for CSS1. The second edition of the standard, CSS2, was adopted in May, 1998; it defines a number of more advanced features, most notably support for absolute positioning of elements. The advanced features of CSS2 are supported only in sixth- generation browsers. Fortunately, however, the crucial positioning features of CSS2 began the standardization process as part of a separate CSS-Positioning (CSS-P) effort, and therefore some of these DHTML-enabling features are available in fourth-generation browsers. Work continues on a third edition of the CSS standard. You can find the CSS specifications and working drafts at http://www.w3.org/Style/CSS/. 18.1.5 CSS Example Example 18-1 is an HTML file that defines and uses a style sheet. It demonstrates the previously described tag name, class, and ID-based style rules, and it also has an example of only as an overview of CSS synt verage of CSS is beyond the scope of this book. Example 18-1. Defining and using Cascading Style Sheets <head> <style type="text/css"> /* Specify that headings display in blue italic text. */ h1, h2 { color: blue; font-style: italic } /* * Any element of class="WARNING" displays in big bold text with large margins * and a yellow background with a fat red border. */ an inline style defined with the style attribute. Remember that this example is meant ax and capabilities. Full co .WARNING { font-weight: bold; font-size: 150%; margin: 0 1in 0 1in; /* top right bottom left */ background-color: yellow; border: solid red 8px; padding: 10px; /* 10 pixels on all 4 sides */ } /* * Text within an h1 or h2 heading within an element with class="WARNING" ng in blue italic * should be centered, in addition to appeari s. */ .WARNING h1, .WARNING h2 { text-align: center } <body> <h1>Cascading Style Sheets Demo</h1> <div class="WARNING"> <h2>Warning</h2> This is a warning! Notice how it grabs your attention with its bold text and bright colors. Also notice that the heading is centered and in blue italics. </div> <p id="P23"> This paragraph is centered<br> and appears in uppercase letters.<br> <span style="text-transform: none"> Here we explicitly use an inline style to override the uppercase letters. </span> </p> </body> 18.2 Element Positioning with CSS For DHTML content developers, the most important feature of CSS is the ability to use ordinary CSS style attributes to specify the visibility, size, and precise position of individual elements of a document. In order to do DHTML programming, it is important to understand how these style attributes work. They are summarized in Table 18-2 /* The single element with id="P23" displays in centered uppercase. */ #P23 { text-align: center; text-transform: uppercase; } </style> </head> and documented in more detail in the sections that follow. Table 18-2. CSS positioning and visibility attributes Attribute(s) Description position Specifies the type of positioning applied to an element top, left Specifies the position of the top and left edges of an element bottom, m and right edges of an element Specifies the position of the botto [...]... example, any of the following three HTML document type declarations cause IE 6 to display documents in standards mode: Netscape 6 and the Mozilla browser handle the width and height attributes correctly... and right padding and left and right border widths to the element width, and you must add the top and bottom padding and top and bottom border widths to the element's height Since width and height specify the element content area only, you might think that left and top (and right and bottom) would be measured relative to the content area of the containing element In fact, the CSS standard specifies... the browser is in standards mode and incorrectly (but compatibly with earlier versions) when the browser is in compatibility mode Standards mode, and hence correct implementation of the CSS "box model," is triggered by the presence of a tag at the start of the document, declaring that the document adheres to the HTML 4.0 (or later) standard or some version of the XHTML standards For example,... document.createElement("DIV"); chart .style. position = "relative"; // Set relative positioning chart .style. width = width + "px"; // Set the chart width chart .style. height = height + "px"; // Set the chart height chart .style. border = "solid black 2px"; // Give it a border chart .style. paddingLeft = "10px"; // Add padding on the left, chart .style. paddingRight = "10px"; // on the right, chart .style. paddingTop = "10px"; // and on the... the data array and create a bar for each datum for(var i = 0; i < data.length; i++) { var bar = document.createElement("div"); // Create div for bar var barheight = data[i] * scale; // Compute height of bar .style. position = "absolute"; and size bar .style. left = (barwidth*i+1+10)+"px"; and chart pad bar .style. top = height-barheight+10+"px"; bar .style. width = (barwidth-2) + "px"; bar .style. height = (barheight-1)... 4 and Netscape 4 were the browsers that introduced DHTML technology to the Internet Both browsers include partial support for the CSS1 standard and support the CSS positioning attributes (which were integrated into the CSS2 standard) that are critical to DHTML Unfortunately, the DOM standard did not exist when these fourth-generation browsers were being developed, so they do not conform to that standard... be altered with the innerHTML property of document elements IE 4 does not conform to the standards here, but it provides adequate alternatives Although traversing and modifying documents is an important part of DHTML, the focus of this chapter is on the dynamic use of CSS styles The good news is that the DOM API described earlier for setting CSS style attributes through the style property was adopted... in the style attribute of the element It is important to understand that the CSS2Properties object you obtain with the style property of an element specifies only the inline styles of the element You cannot use the properties of the CSS2Properties object to obtain information about the style- sheet styles that apply to the element By setting properties on this object, you are defining inline styles... string unless that paragraph has a style attribute that overrides the style sheet setting Thus, although the CSS2Properties object is useful for setting styles that override any other styles, it does not provide a way to query the CSS cascade and determine the complete set of styles that apply to a given element Later in this chapter we will briefly consider the getComputedStyle( ) method, which does provide... implement the width and height attributes incorrectly and include an element's border and padding (but not its margins) For example, if you set the width of an element to 100 pixels and place a 10-pixel margin and a 5-pixel border on the left and right, the content area of the element ends up being only 70 pixels wide in these buggy versions of Internet Explorer In IE 6, the CSS position and size attributes . list -style [ list -style- type || list -style- position || list- style- image ] list -style- image url( url ) | none list -style- position inside | outside list -style- type. is that the user style sheet overrides the default browser style sheet, author style sheets override the user style sheet, and inline styles override everything.

Ngày đăng: 05/10/2013, 12:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan