What Can You Use to Make an H2 Have One Font Family Sometimes and Another Other Times?

Chapter ii
CSS

As we explained in the previous chapter, HTML elements enable Web page designers to marking up a document as to its structure. The HTML specification lists guidelines on how browsers should display these elements. For example, yous tin be reasonably sure that the contents of a strong element will be displayed bold-faced. Besides, you lot tin can pretty much trust that virtually browsers will brandish the content of an h1 element using a big font size... at least bigger than the p element and bigger than the h2 element. But beyond trust and hope, you don't accept any control over how your text appears.

CSS changes that. CSS puts the designer in the commuter's seat. Nosotros devote much of the remainder of this book to explaining what you tin can do with CSS. In this chapter, nosotros brainstorm by introducing you to the nuts of how to write fashion sheets and how CSS and HTML work together to describe both the construction and appearance of your document.

Rules and Fashion Sheets

To start using CSS, you don't even have to write style sheets. Affiliate 16 will tell yous how to point to existing mode sheets on the Spider web.

There are two ways to create CSSs. You can either apply a normal text editor and write the style sheets "by hand," or yous can apply a defended tool - for example a Spider web folio design application - which supports CSS. The dedicated tools let you to create style sheets without learning the syntax of the CSS language. Even so, in many cases the designer will want to tweak the style canvas past hand later, so we recommend that you learn to write and edit CSSs past hand. Permit's get started!

H1 { color: green }

What you see above is a simple CSS dominion that contains one dominion. A rule is a statement about one stylistic attribute of one or more elements. A style sheet is a set of one or more than rules that utilize to an HTML document. The rule in a higher place sets the color of all first-level headings (h1). Let's take a quick await at what the visual upshot of the dominion could exist:

Figure 2.1

[image]

We volition now commencement dissecting the rule.

Beefcake of a dominion

A dominion consists of 2 parts:

  • Selector - the function before the left curly brace
  • Declaration - the role within the curly braces

    [image]

The selector is the link between the HTML certificate and the manner. It specifies what elements are afflicted by the announcement. The annunciation is that part of the rule that sets forth what the issue will be. In the example above, the selector is h1 and the declaration is "color: green." Hence, all h1 elements will be afflicted by the declaration, that is, they will be turned green. (The color property just affects the foreground text color, in that location are other properties for background, border, etc.)

The above selector is based on the blazon of the chemical element: it selects all elements of blazon "h1." This kind of selector is called blazon selector. Any HTML element type can be used as a type selector. Type selectors are the simplest kind of selectors. Nosotros discuss other kinds of selectors in See CSS selectors. , "CSS selectors."

Anatomy of a declaration

A annunciation has 2 parts separated past a colon:

  • Holding - that office before the colon
  • Value - that function after the colon

    [image]

The property is a quality or characteristic that something possesses. In the previous example, information technology is color. CSS2 (see split up box) defines around 120 properties and we can assign values to all of them.

The value is a precise specification of the belongings. In the case, it is "green," but it could just as hands exist blue, carmine, yellow, or some other color.

The diagram below shows all ingredients of a rule. The curly braces ({ }) and colon (:) make it possible for the browser to distinguish between the selector, property, and value.

Figure ii.2 Diagram of a rule.

[image]

Grouping selectors and rules

In designing CSS, brevity was a goal. We figured that if we could reduce the size of style sheets, we could enable designers to write and edit fashion sheets "by manus." Also, short fashion sheets load faster than longer ones. CSS therefore includes several mechanisms to shorten style sheets by manner of grouping selectors and declarations.

For case, consider these iii rules:

H1 { font-weight: bold } H2 { font-weight: bold } H3 { font-weight: bold }            

All three rules have exactly the aforementioned annunciation - they set the font to be bold. (This is done using the font-weight property, which nosotros talk over in See Fonts. .) Since all three declarations are identical, we can group the selectors into a comma-separated list and but list the announcement once, like this:

H1, H2, H3 { font-style: assuming }

This rule volition produce the same result as the starting time three.

A selector may accept more than than ane annunciation. For instance, we could write a style sheet with these two rules:

H1 { color: green } H1 { text-align: centre }

In this instance, we gear up all h1s to be green and to be centered on the canvas. (This is done using the text-align property, discussed in Chapter  5 .)

But we can accomplish the same effect faster by grouping the declarations that relate to the aforementioned selector into a semicolon-separated list, like this:

H1 {   color: light-green;   text-align: center; }

All declarations must exist contained within the pair of curly braces. A semicolon separates the declarations and may - but doesn't accept to - besides appear at the end of the last declaration. Also, to make your code easier to read, we suggest you lot place each declaration on its own line, as we did here. (Browsers won't care, they'll only ignore all the actress whitespace and line breaks.)

Now you lot have the basics of how to create CSS rules and style sheets. Still, you're not done yet. In society for the style sail to have whatever effect you lot have to "mucilage" your style sail to your HTML document.

"Gluing" Manner Sheets to the Document

For whatsoever style sail to touch on the HTML document, it must be "glued" to the certificate. That is, the style sheet and the HTML certificate must be combined and then that they tin can piece of work together to present the document. This can exist done in any of four means:

  1. Apply the basic, document-wide way sheet for the certificate by using the style element.
  2. Apply a way canvas to an individual element using the manner attribute.
  3. Link an external mode sheet to the certificate using the link element.
  4. Import a style canvass using the CSS @import note.

In the side by side section, nosotros talk over the get-go method: using the fashion element. We talk over using the manner aspect in Chapter 4 , "CSS selectors," and using the link element and the @import notation in Chapter 16 , "External style sheets."

Gluing past using the Manner element

You tin can glue the style sail and the HTML certificate together by putting the style sheet inside a style chemical element at the top of your certificate. The mode chemical element was introduced in HTML specifically to allow style sheets to be inserted within HTML documents. Here's a style sail (shown in assuming) glued to a sample certificate past using the style chemical element. The outcome is shown in Effigy  ii.3 .

<HTML>   <TITLE>Bach's abode page</Championship>                              <Mode>     H1, H2 { color: green }   </STYLE>              <BODY>     <H1>Bach'due south home folio</H1>     <P>Johann Sebastian Bach was a prolific         composer. Among his works are:     <UL>       <LI>the Goldberg Variations       <LI>the Brandenburg Concertos       <LI>the Christmas Oratorio     </UL>     <H2>Historical perspective</H2>     <P>Bach composed in what has been referred to as       the Baroque menses.   </BODY> </HTML>

Effigy ii.iii The result of adding to a style sail a rule to turn h1south dark-green and so gluing the style sheet to the document using the mode elements. (endeavor it)

[image]

Notice that the way chemical element is placed after the title element and before the body element. The title of a document does not show up on the canvas, and so it is non afflicted past CSS styles.

The content of a style element is a style canvas. Nonetheless, whereas the content of such elements as h1, p, and ul appears on the canvas, the content of a style element does not show on the sheet. Rather, it is the issue of the content of the mode chemical element - the mode canvass - that appears on the canvas. Then y'all don't encounter "{ color: light-green }" displayed on your screen; you see instead two h1 elements colored greenish. No rules have been added that affect whatever of the other elements, so those elements appear in the browser's default color.

Browsers and CSS

For an updated overview of bachelor browsers, run across the W3C overview folio

For CSS to work as described in this book, you must employ a CSS-enhanced browser, that is, a browser that supports CSS. A CSS-enhanced browser volition recognize the style element equally a container for a style sheet and present the certificate appropriately. Most browsers that are distributed today support CSS, for example Microsoft Cyberspace Explorer four (IE4), Netscape Navigator four (NS4) and Opera iii.5 (O3.5). Conservative estimates bespeak that more than than one-half the people on the Web utilize a CSS-enhanced browser, and the figures are steadily rising. Chances are that the people you communicate with have CSS-enhanced browsers. If not, give them a reason to upgrade!

The best source for information on how dissimilar browsers back up CSS is WebReview's charts

Alas, not all CSS implementations are perfect. When you start experi­menting with style sheets, you will shortly notice that each browser comes with a set of bugs and limitations. In general, newer browsers comport better than older ones. IE4 and O3.5 are among the best, and Netscape'south adjacent offering - code-named Gecko - also promises much improved back up for CSS.

Those who don't utilise CSS-enhanced browsers can however read pages that employ style sheets. CSS was carefully designed then that all content should remain visible even if the browser knows nothing virtually CSS. Some browsers, such equally Netscape's Navigator version 2 and 3 don't support style sheets but they know plenty near the mode chemical element to fully ignore information technology. Adjacent to supporting way sheets, this is the correct behavior.

However, other browsers that do non know the mode chemical element, such as Netscape's Navigator i and Microsoft Internet Explorer 2, volition ignore the style tags but display the content of the fashion element. Thus, the user will end up with the way canvas printed on the pinnacle of the sail. At the time of writing, only a few per centum of Web users will feel this trouble. To avoid this, y'all tin put your style sheet inside an HTML comment, which we discussed in Chapter  1 . Because comments don't brandish on the screen, by placing your manner sheet inside an HTML annotate, you preclude the oldest browsers from displaying the fashion element'south content. CSS-enhanced browsers are aware of this play tricks, and will treat the content of the style chemical element as a style canvas.

Call up that HTML comments commencement with <!-- and end with -->. Here's an extract from the previous code case that shows how you write a fashion sheet in an HTML annotate. The comment encloses the way element content but:

<HTML>   <Championship>Bach's dwelling house page</Championship>   <STYLE>                          <!--            H1 { colour: green }                          -->            </STYLE>   <BODY>     ..   </BODY> </HTML>

CSS as well has its own set of comments that you lot can use within the mode sheet. A CSS comment begins with "/*" and ends with "*/." (Those familiar with the C programming linguistic communication will recognize these.) CSS rules inside a CSS annotate volition not have whatsoever effect on the presentation of the document.

The browser also needs to be told that you are working with CSS fashion sheets. CSS is currently the simply style sheet language in use with HTML docu­ments and we don't expect this to modify. For XML the situation might exist unlike. Just just as there is more than one paradigm format (GIF, JPEG and PNG come to mind), there could be more than than one style sheet linguistic communication. So information technology'southward a practiced habit to tell browsers that they are dealing with CSS. (In fact, HTML requires you to.) This is done with the type attribute of the mode ­element. The value of type indicates what type of style sail is beingness used. For CSS, that value is "text/css." The following is an excerpt from our previous sample document that shows you how you would write this (in combination with the use of the HTML comment):

<HTML>   <TITLE>Bach'southward dwelling page</TITLE>   <STYLE            Type="text/css">            <!--       H1 { color: green }     -->   </STYLE>   <Trunk>     ..   </BODY> </HTML>          

When the browser loads a document, information technology checks to see if information technology understands the style sheet language. If it does, it will try to read the canvass, otherwise it will ignore it. The blazon aspect (run into Chapter  one for a discussion on HTML attributes) on the style element is a way to allow the browser know which style sheet language is being used. The type attribute must be included.

To make examples easier to read, we have chosen not to wrap style sheets in HTML comments, but we do use the type attribute throughout this book.

Tree structures and inheritance

Recollect from Chapter  1 the discussion most HTML representing a document with a tree-like structure and how elements in HTML have children and parents. There are many reasons for having tree-structured documents. For style sheets, there is ane very good reason: inheritance. Just every bit children inherit from their parents, so practise HTML elements. Instead of inheriting genes and money, HTML elements inherit stylistic properties.

Let'southward starting time by taking a look at the sample certificate:

<HTML>   <Championship>Bach's home page</TITLE>   <Torso>     <H1>Bach'due south abode page</H1>     <P>Johann Sebastian Bach was a       <STRONG>prolific</STRONG> composer. Among his         works are:     <UL>       <LI>the Goldberg Variations       <LI>the Brandenburg Concertos       <LI>the Christmas Oratorio     </UL>   </BODY> </HTML>

The tree structure of this document is:

[image]

Through inheritance, CSS property values set on one element volition be transferred down the tree to its descendants. For example, our examples have up to at present set the colour to exist green for h1 and h2 elements. Now, say, y'all would like to prepare the aforementioned colour on all elements in your certificate. You could exercise this past listing all chemical element types in the selector:

<Style TYPE="text/css">   H1, H2, P, LI { color: greenish } </Style>

However, near HTML documents are more complex than our sample docu­ment, and your manner sail would soon go long. At that place is a better - and shorter - manner. Instead of setting the style on each element type, we set up it on their mutual antecedent, the body element:

<Way Blazon="text/css">   BODY { color: greenish } </STYLE>

Since other elements inherit backdrop from the body element, they will all inherit the colour green (Figure  2.4 ).

Effigy ii.4 The result of inheritance. (endeavor information technology)

[image]

Equally y'all take seen higher up, inheritance is a transport vehicle that will distribute stylistic properties to descendants of an element. Since the body element is a common ancestor for all visible elements, body is a convenient selector when y'all want to prepare stylistic rules for the unabridged document.

Overriding Inheritance

In the previous example, all elements were given the same color through inheritance. Sometimes, however, children don't look like their parents. Not surprisingly, CSS besides accounts for this. Say you lot would like for h1 elements to be blue while the rest should be greenish. This is easily expressed in CSS:

<STYLE Type="text/css">   BODY { color: light-green }   H1 { color: navy } </STYLE>

Since h1 is a kid chemical element of body (and thereby inherits from trunk), the two rules in the in a higher place way sail are conflicting. The kickoff one sets the color of the body element - and thereby also the colour of h1 through inheritance - while the second one sets the colour specifically on the h1 element. Which rule volition win? Permit'south find out:

The reason why the second rule wins is that information technology is more specific than the first. The beginning rule is very full general - information technology affects all elements on the canvas. The ­2nd rule only affects h1 elements in the document and is therefore more specific.

If CSS had been a programming language, the order in which the rules were specified would determine which of them would win. CSS is not a programming linguistic communication, and in the to a higher place case, the order is irrelevant. The result is exactly the aforementioned if we utilize this style sheet:

<STYLE TYPE="text/css">   H1 { colour: navy }   BODY { color: dark-green } </Style>

CSS has been designed to resolve conflicts betwixt fashion sheet rules like the one to a higher place. Specificity is i aspect of that. You can find the details in Chapter  15 , "Cascading and inheritance."

Properties that don't inherit

As a general rule, properties in CSS inherit from parent to child elements every bit described in the previous examples. Some backdrop, withal, don't inherit and there is always a good reason why. We will use the background property (described in Affiliate eleven) as an example of a belongings that doesn't inherit.

Permit's say you want to ready a groundwork image for a page. This is a common issue on the Spider web. In CSS, you tin can write:

<HTML>   <Title>Bach's home page</Title>   <Way Type="text/css">     BODY {       background: url(texture.gif) white;       color: black;     }   </STYLE>   <BODY>     <H1>Bach'due south <EM>home</EM> page</H1>     <P>Johann Sebastian Bach was a prolific       composer.   </Trunk> </HTML>

The background holding has a URL ("texture.gif") that points to a background image as value. When the image is loaded, the sheet looks like:

There are a few noteworthy things in the above example:

  • The background image covers the surface like a wallpaper - too the backgrounds of the h1 and p element have been covered. This is not due to inheritance, but to the fact that unless otherwise set, all backgrounds are transparent. And so, since we haven't fix the backgrounds of the h1 or p element to something else, the parent chemical element, body, will smoothen through.
  • In addition to the URL of the epitome, a color (white) has also been speci­fied equally the background. In instance the image tin can't exist found, you lot will see the color instead.
  • The colour of the body element has been set to blackness. To ensure contrast between the text and the background, it is a good habit to always ready a color when the background belongings is set.

So, exactly why doesn't the background property inherit? Visually, the event of transparency is similar to inheritance: it looks like all elements take the same backgrounds. There are ii reasons: first, transparent backgrounds are faster to brandish (there is nothing to display!) than other ­backgrounds. Second, since background images are aligned relative to the element they vest to, you would otherwise not always finish upward with a shine groundwork surface.

Common tasks with CSS

Setting colors and backgrounds - as described above - are amid the most common tasks performed by CSS. Other common tasks include setting fonts and white space around elements. This section gives you a guided tour of the about commonly used properties in CSS.

Common tasks: fonts

Permit's start with fonts. If yous have used desktop publishing applications in the past, you should be able to read this little style sheet:

H1 { font: 36pt serif }

The rule above sets the font for h1 elements. The first function of the value - 36pt - sets the font size to be 36 points. A "point" is an onetime typographic unit which has survived into the digital age. In the side by side chapter we volition tell you why you should utilise the "em" unit instead of "pt" but for now we'll stick to points. The second part of the value - serif - tells the browser to utilize a font with serifs (the footling hooks at the ends of the strokes, Chapter  5 volition tell yous all nigh them). The more decorated serif fonts conform Bach's domicile page well since the mod sans-serif fonts (fonts without serifs) weren't used in his time. Here is the effect:

The font holding is a shorthand belongings for setting several other properties at one time. By using information technology, you can shorten your fashion sheets and fix values on all properties it replaces. If you choose to use the expanded version, yous would have to set all of these to supervene upon the example above:

H1 {   font-size: 36pt;   font-family: serif;   font-style: normal;   font-weight: normal;   font-variant: normal;   line-height: normal; }

Sometimes you only want to fix 1 of these. For example, yous may want to slant the text in some elements. Here is an example:

UL { font-style: italic }

The font-style property will not change the font size or the font family, it will only slant the existing font. When gear up on the ul chemical element, the li elements inside will become slanted, since font-style is inherited. Here is the result when practical to the test page you know by now:

Similarly, the font-weight property is used to change the weight - thickness - of the messages. You tin can further emphasize the list items past setting their ancestor to be assuming:

UL {   font-style: italic;   font-weight: bold; }            

Which yields:

The concluding properties, font-variant and line-summit, haven't been widely supported in browsers upward to now and are therefore not equally commonly used yet.

Common tasks: margins

Setting space around elements is a basic tool in typography. The headline above this paragraph has space above it and (slightly less) infinite below it. This paragraph, as printed in the book, has space on the left and (slightly less) on the correct. CSS tin be used to express how much space there should be around dissimilar kinds of elements.

Past default, your browser knows quite a chip about how to display the different kinds of elements in HTML. For example, information technology knows that lists and blockquote elements should exist indented to set them apart from the residue of the text. Equally a designer, y'all tin can build on these settings while at the aforementioned time provide your own refinements. Allow's use the blockquote element as an case. Here's a exam document:

<HTML>   <Championship>Fredrick the Swell meets Bach</TITLE>   <Trunk>     <P>Ane evening, just every bit Fredrick the Dandy was       getting his flute ready, and his musicians       were assembled, an officer brought him a       list of the strangers who had arrived. With       his flute in his hand he ran over the list,       just immediately turned to the assembled       musicians, and said, with a kind of       agitation:     <BLOCKQUOTE>"Gentlemen, old Bach is come up."     </BLOCKQUOTE>     <P>The flute was at present laid aside, and old Bach, who       had alighted at his son's lodgings, was immediately       summoned to the Palace.   </BODY> </HTML>

The screen-shot below is how a typical HTML browser would display the certificate:

As yous can run across, the browser has added space on all sides of the quoted text. In CSS, this space is called "margins" and all elements have margins on all 4 sides. The backdrop are chosen: margin-superlative, margin-right, margin-lesser, and margin-left. You can change how the blockquote element is displayed by writing a little way canvas:

BLOCKQUOTE {   margin-top: 1em;   margin-right: 0em;   margin-bottom: 1em;   margin-left: 0em;   font-style: italic; }

The "em" unit will be treated in item in the adjacent chapter, but nosotros can already now reveal its secret: it scales relative to the font size. So, the above instance will result in the vertical margins existence every bit high equally the font size (1em) of the blockquote, and horizontal margins having nix width. To make sure the quoted text can still exist distinguished, information technology has been given an italic camber. The event is:

Just like font is a shorthand property to set several font-related properties at once, margin is a shorthand property which sets all margin backdrop. The higher up case tin can therefore be written:

BLOCKQUOTE {   margin: 1em 0em 1em 0em;   font-style: italic; }

The starting time role of the value - 1em - is assigned to margin-top. From in that location it's clockwise: 0em is assigned to margin-right, 1em is assigned to margin-bottom, and 0em is assigned to margin-left.

With the left margin set to zero, the quoted text needs more styling to set up it apart from the rest of the text. Setting font-mode to italic helps, and adding a groundwork color further amplifies the quote:

BLOCKQUOTE {   margin: 1em 0em 1em 0em;   font-fashion: italic;   background: #EDB; }

The result is:

Equally expected, the background color behind the quote has inverse. Unlike previous examples, the colour was specified in red/dark-green/blue (RGB) components. RGB colors are described in particular in Affiliate  11 .

I stylistic trouble in the example in a higher place is that the background color barely covers the quoted text. The space around the quote - the margin area - does not use the element's background color. CSS has some other kind of infinite, called padding, which uses the groundwork colour of the element. In other respects the padding backdrop are like the margin properties: they add space around an chemical element. Let'due south add some padding to the quote:

BLOCKQUOTE {   margin: 1em 0em 1em 0em;   font-mode: italic;   background: #EDB;   padding: 0.5em; }

The result of setting the padding is added space between the text and the rectangle that surrounds information technology:

Notice that the padding property was only given ane value (0.5em). Just like the margin property, padding could have taken iv values which would have been assigned to the top, right, bottom and left padding respectively. However, when the same value is to be assault all sides, list it in one case will suffice. This is true both for padding and margin (as well as some other border properties, which are described in See Space effectually boxes. ).

Common tasks: links

To brand it easier for users to scan in hypertext documents, the links should have a manner that distinguishes them from normal text. HTML browsers have often underlined hyperlink text. Also, various color schemes take been used to point if the user has previously visited the link or non. Since hyperlinks are such a fundamental part of the Spider web, CSS has special support for styling them. Here's a simple example:

A:link { text-decoration: underline }

The above instance specifies that unvisited links should be underlined:

The links are underlined, every bit nosotros take specified, but they are also blueish, which we have not. When authors practise not specify all possible styles, browsers use default styles to fill in the gaps. The interaction betwixt writer styles, browser default styles and user styles (the user'southward ain preferences) is ­another example of CSS'south disharmonize resolution rules. It is chosen the cascade (the "C" of CSS). We will discuss the cascade below.

The selector (A:link) deserves special mentioning. You probably ­recognize "A" as being an HTML element, only the final part is new. ":link" is 1 of several then-called pseudo-classes in CSS. Pseudo-classes are used to give style to elements based on data outside of the certificate itself. For case, the writer of the certificate tin can't know if a certain link will exist visited or non. Pseudo-classes are described in particular in Affiliate  four , and we'll only give a few more examples hither:

A:visited { text-decoration: none }

This rule gives style to visited links, just like A:link gave manner to unvisited links. Here is a slightly more than complex example:

A:link, A:visited { text-decoration: none } A:hover { background: cyan }

The last rule introduces a new pseudo-class :hover. Assuming the user is moving a pointing device (like a mouse), the specified style will be applied to the element when the user moves the arrow over ("hovers" over) the link. A common effect is to change the background color. Here is what information technology looks similar:

The :hover pseudo-class has an interesting history. It was introduced in CSS2 after the hover effect became popular amid JavaScript programmers. The JavaScript solution requires complicated code compared to the CSS pseudo-class and this is an example of CSS picking up effects that have go popular amidst Web designers.

A word about Cascading

A fundamental feature of CSS is that more than than one mode canvas tin influence the presentation of a certificate. This feature is known as cascading considering the dissimilar manner sheets are thought of as coming in a series. Cascading is a fundamental feature of CSS, because we realized that any single document could very likely end upwards with style sheets from multiple sources: the browser, the designer, and perhaps the user.

In the final ready of examples yous saw that the text color of the links turned bluish without that beingness specified in the style sheet. Also, the browser knew how to format blockquote and h1 elements without being told and then explicitly. Everything that the browser knows most formatting is stored in the browser's default manner sail and is merged with author and user style sheets when the document is displayed.

We have known for years that designers want to develop their own mode sheets. However, we discovered that users, too, want the selection of influencing the presentation of their documents. With CSS, they tin can do this by supplying a personal mode sheet that will be merged with the browser's and the designer's style sheets. Any conflicts between the diverse style sheets are resolved past the browser. Usually, the designer's style sail will accept the strongest claim on the certificate, followed by the user's, and and so the browser'southward default. However, the user can say that a rule is very import­ant and it will and then override any author or browser styles.

We go into details about cascading in Chapter  15 , "Cascading and inheritance." Earlier that, there is much to learn about fonts, space and ­colors.

charbonneauexceer.blogspot.com

Source: https://www.w3.org/Style/LieBos2e/enter/Overview.en.html

Belum ada Komentar untuk "What Can You Use to Make an H2 Have One Font Family Sometimes and Another Other Times?"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel