banner



How Do You Add A Background Color For All <h1> Elements?

Affiliate two
CSS

Equally we explained in the previous chapter, HTML elements enable Web page designers to marker upwardly a document every bit to its construction. The HTML specification lists guidelines on how browsers should display these elements. For instance, you can be reasonably sure that the contents of a stiff chemical element will be displayed bold-faced. Also, you can pretty much trust that most browsers will display the content of an h1 element using a big font size... at least bigger than the p chemical element and bigger than the h2 chemical element. But beyond trust and promise, you don't have whatever control over how your text appears.

CSS changes that. CSS puts the designer in the driver's seat. We devote much of the rest of this book to explaining what yous can practice with CSS. In this chapter, nosotros begin past introducing you to the basics of how to write fashion sheets and how CSS and HTML work together to describe both the structure and appearance of your certificate.

Rules and Style Sheets

To start using CSS, you don't even have to write style sheets. Chapter 16 will tell you lot how to point to existing way sheets on the Web.

There are two ways to create CSSs. You can either use a normal text editor and write the fashion sheets "by hand," or you can use a dedicated tool - for instance a Web folio blueprint application - which supports CSS. The defended tools let you to create style sheets without learning the syntax of the CSS language. All the same, in many cases the designer volition want to tweak the style sail by hand afterward, so nosotros recommend that you learn to write and edit CSSs by paw. Let's become started!

H1 { color: dark-green }

What y'all see above is a simple CSS rule that contains one rule. A rule is a statement most one stylistic aspect of 1 or more elements. A style sheet is a set of one or more rules that utilise to an HTML document. The rule in a higher place sets the color of all first-level headings (h1). Let's have a quick look at what the visual upshot of the dominion could be:

Effigy 2.1

[image]

We volition now kickoff dissecting the rule.

Beefcake of a rule

A rule consists of two parts:

  • Selector - the part before the left curly brace
  • Proclamation - the part within the curly braces

    [image]

The selector is the link betwixt the HTML document and the style. Information technology specifies what elements are afflicted by the annunciation. The declaration is that part of the dominion that sets forth what the result will be. In the example to a higher place, the selector is h1 and the announcement is "color: green." Hence, all h1 elements volition be afflicted by the declaration, that is, they volition be turned green. (The colour property just affects the foreground text color, there are other properties for background, border, etc.)

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

Beefcake of a annunciation

A declaration has 2 parts separated by a colon:

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

    [image]

The property is a quality or characteristic that something possesses. In the previous example, it is colour. CSS2 (run into split up box) defines around 120 backdrop and we tin assign values to all of them.

The value is a precise specification of the property. In the example, it is "light-green," merely information technology could just as easily be blue, crimson, yellow, or some other color.

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

Effigy ii.2 Diagram of a dominion.

[image]

Grouping selectors and rules

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

For case, consider these three rules:

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

All 3 rules take exactly the same declaration - they set up the font to be bold. (This is done using the font-weight holding, which we hash out in See Fonts. .) Since all iii declarations are identical, we can grouping the selectors into a comma-separated listing and only list the announcement once, similar this:

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

This rule volition produce the same issue as the first three.

A selector may accept more than one proclamation. For example, nosotros could write a fashion canvass with these two rules:

H1 { color: green } H1 { text-marshal: center }

In this case, nosotros prepare all h1south to be green and to be centered on the canvas. (This is done using the text-align property, discussed in Chapter  5 .)

Simply we tin can attain the aforementioned effect faster by grouping the declarations that relate to the same selector into a semicolon-separated list, similar this:

H1 {   color: greenish;   text-marshal: center; }

All declarations must be independent within the pair of curly braces. A semicolon separates the declarations and may - but doesn't have to - also appear at the end of the terminal declaration. Also, to make your code easier to read, we propose you place each proclamation on its own line, every bit we did here. (Browsers won't intendance, they'll just ignore all the extra whitespace and line breaks.)

Now you lot have the nuts of how to create CSS rules and fashion sheets. Nonetheless, y'all're not done withal. In order for the way sail to have any upshot you have to "glue" your style sheet to your HTML certificate.

"Gluing" Manner Sheets to the Certificate

For any fashion sheet to bear upon the HTML document, it must be "glued" to the document. That is, the style sheet and the HTML certificate must be combined so that they can piece of work together to nowadays the document. This can be done in whatever of four ways:

  1. Utilise the basic, document-wide style sheet for the document by using the style element.
  2. Employ a style sheet to an individual element using the mode aspect.
  3. Link an external style sail to the certificate using the link element.
  4. Import a style canvass using the CSS @import notation.

In the side by side section, we discuss the first method: using the style element. We discuss using the way attribute in Chapter 4 , "CSS selectors," and using the link element and the @import notation in Chapter xvi , "External manner sheets."

Gluing past using the STYLE element

You can glue the style sheet and the HTML document together by putting the fashion sheet inside a style chemical element at the height of your document. The style element was introduced in HTML specifically to allow mode sheets to be inserted inside HTML documents. Here's a fashion sheet (shown in bold) glued to a sample document by using the style element. The upshot is shown in Figure  ii.iii .

<HTML>   <Title>Bach's home page</Title>                              <STYLE>     H1, H2 { colour: green }   </Manner>              <Torso>     <H1>Bach's dwelling house page</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 equally       the Baroque menses.   </Body> </HTML>

Figure 2.3 The result of adding to a style sail a rule to plow h1south greenish and then gluing the mode sheet to the document using the style elements. (endeavour it)

[image]

Notice that the style element is placed after the championship element and before the body element. The title of a document does non show up on the canvas, then information technology is not affected by CSS styles.

The content of a style element is a style canvas. Nevertheless, 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 sail. Rather, information technology is the effect of the content of the manner element - the style sheet - that appears on the sail. So you don't see "{ color: green }" displayed on your screen; you come across instead two h1 elements colored green. No rules have been added that affect whatsoever of the other elements, and so those elements appear in the browser's default colour.

Browsers and CSS

For an updated overview of available browsers, see the W3C overview folio

For CSS to work as described in this volume, y'all must use a CSS-enhanced browser, that is, a browser that supports CSS. A CSS-enhanced browser will recognize the style element as a container for a fashion sheet and nowadays the certificate accordingly. Nigh browsers that are distributed today support CSS, for example Microsoft Net Explorer iv (IE4), Netscape Navigator four (NS4) and Opera 3.5 (O3.5). Conservative estimates indicate that more than half the people on the Web use a CSS-enhanced browser, and the figures are steadily rising. Chances are that the people you lot communicate with have CSS-enhanced browsers. If not, requite them a reason to upgrade!

The all-time source for data on how different browsers support CSS is WebReview's charts

Alas, not all CSS implementations are perfect. When you lot outset experi­menting with style sheets, you will soon notice that each browser comes with a set of bugs and limitations. In general, newer browsers behave meliorate than older ones. IE4 and O3.5 are among the best, and Netscape'due south next offering - lawmaking-named Gecko - likewise promises much improved back up for CSS.

Those who don't employ CSS-enhanced browsers can nonetheless read pages that use style sheets. CSS was carefully designed so that all content should remain visible even if the browser knows nothing about CSS. Some browsers, such as Netscape's Navigator version ii and 3 don't support style sheets merely they know enough about the style element to fully ignore it. Next to supporting style sheets, this is the right behavior.

However, other browsers that practice not know the style element, such as Netscape'southward Navigator i and Microsoft Cyberspace Explorer 2, will ignore the manner tags but display the content of the style element. Thus, the user will end up with the fashion sheet printed on the top of the canvas. At the time of writing, only a few percent of Web users volition experience this trouble. To avert this, you can put your style canvas inside an HTML comment, which nosotros discussed in Chapter  1 . Because comments don't display on the screen, by placing your style sheet inside an HTML annotate, you forbid the oldest browsers from displaying the fashion element'south content. CSS-enhanced browsers are enlightened of this play a trick on, and will treat the content of the style element equally a style sheet.

Recall that HTML comments showtime with <!-- and end with -->. Here'due south an extract from the previous code example that shows how you write a fashion sheet in an HTML comment. The comment encloses the manner element content only:

<HTML>   <TITLE>Bach'south home folio</Championship>   <Mode>                          <!--            H1 { color: green }                          -->            </STYLE>   <BODY>     ..   </BODY> </HTML>

CSS too has its own set up of comments that you can utilize within the manner sail. A CSS annotate begins with "/*" and ends with "*/." (Those familiar with the C programming linguistic communication will recognize these.) CSS rules inside a CSS comment volition not have any upshot on the presentation of the certificate.

The browser also needs to be told that you lot are working with CSS style sheets. CSS is currently the just style sheet linguistic communication in use with HTML docu­ments and nosotros don't look this to change. For XML the state of affairs might exist unlike. But just as at that place is more than ane image format (GIF, JPEG and PNG come to mind), there could be more than one style sail language. So it's a skillful addiction to tell browsers that they are dealing with CSS. (In fact, HTML requires you to.) This is done with the type aspect of the manner ­element. The value of type indicates what blazon of way sheet 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 lot would write this (in combination with the use of the HTML comment):

<HTML>   <Title>Bach's habitation folio</Title>   <Way            TYPE="text/css">            <!--       H1 { color: green }     -->   </STYLE>   <Body>     ..   </BODY> </HTML>          

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

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

Tree structures and inheritance

Recall from Chapter  1 the give-and-take well-nigh HTML representing a document with a tree-like construction 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. Merely equally children inherit from their parents, then practise HTML elements. Instead of inheriting genes and money, HTML elements inherit stylistic backdrop.

Let's start past taking a look at the sample document:

<HTML>   <TITLE>Bach's home page</Title>   <Torso>     <H1>Bach'due south habitation 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>   </Trunk> </HTML>

The tree structure of this document is:

[image]

Through inheritance, CSS holding values set on one chemical element will exist transferred downwards the tree to its descendants. For case, our examples have up to at present set the colour to be green for h1 and h2 elements. Now, say, you lot would like to set up the same colour on all elements in your document. Y'all could exercise this past listing all element types in the selector:

<STYLE TYPE="text/css">   H1, H2, P, LI { color: green } </Way>

However, near HTML documents are more complex than our sample docu­ment, and your style sheet would before long get long. At that place is a improve - and shorter - way. Instead of setting the style on each element blazon, nosotros set information technology on their common antecedent, the body element:

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

Since other elements inherit properties from the trunk element, they will all inherit the color green (Effigy  2.4 ).

Figure 2.iv The result of inheritance. (try it)

[image]

Every bit you lot have seen above, inheritance is a ship vehicle that will distribute stylistic properties to descendants of an chemical element. Since the trunk chemical element is a mutual ancestor for all visible elements, body is a convenient selector when y'all desire to set stylistic rules for the entire document.

Overriding Inheritance

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

<STYLE TYPE="text/css">   Trunk { color: greenish }   H1 { color: navy } </Fashion>

Since h1 is a child element of trunk (and thereby inherits from body), the two rules in the in a higher place style sheet are alien. The first one sets the color of the body element - and thereby besides the color of h1 through inheritance - while the 2nd i sets the colour specifically on the h1 element. Which rule will win? Let's notice out:

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

If CSS had been a programming linguistic communication, the social club in which the rules were specified would determine which of them would win. CSS is non a programming language, and in the above case, the guild is irrelevant. The result is exactly the same if we use this style canvass:

<Way TYPE="text/css">   H1 { color: navy }   Torso { colour: green } </STYLE>

CSS has been designed to resolve conflicts between style canvas rules like the i above. Specificity is ane aspect of that. You lot tin can find the details in Chapter  15 , "Cascading and inheritance."

Properties that don't inherit

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

Let's say you want to set up a background image for a page. This is a common upshot on the Web. In CSS, you can write:

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

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

In that location are a few noteworthy things in the above example:

  • The background epitome covers the surface like a wallpaper - also the backgrounds of the h1 and p element have been covered. This is not due to inheritance, only to the fact that unless otherwise set, all backgrounds are transparent. So, since we haven't ready the backgrounds of the h1 or p element to something else, the parent element, body, will shine through.
  • In addition to the URL of the epitome, a color (white) has as well been speci­fied as the groundwork. In example the paradigm can't be plant, yous will see the color instead.
  • The color of the torso element has been prepare to black. To ensure contrast betwixt the text and the background, it is a good habit to always set up a color when the background property is ready.

So, exactly why doesn't the background property inherit? Visually, the consequence of transparency is like to inheritance: it looks like all elements accept the same backgrounds. There are two reasons: first, transparent backgrounds are faster to brandish (there is nada to display!) than other ­backgrounds. 2d, since background images are aligned relative to the element they belong to, you would otherwise not always end upwardly with a shine background surface.

Mutual tasks with CSS

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

Common tasks: fonts

Let's start with fonts. If you lot have used desktop publishing applications in the past, you should exist able to read this piffling way canvas:

H1 { font: 36pt serif }

The rule to a higher place sets the font for h1 elements. The offset office of the value - 36pt - sets the font size to be 36 points. A "point" is an old typographic unit of measurement which has survived into the digital age. In the side by side chapter we will tell y'all why yous should utilize the "em" unit of measurement instead of "pt" only for at present we'll stick to points. The second part of the value - serif - tells the browser to use a font with serifs (the fiddling hooks at the ends of the strokes, Chapter  5 volition tell y'all all about them). The more decorated serif fonts suit Bach'due south habitation page well since the modern sans-serif fonts (fonts without serifs) weren't used in his time. Here is the issue:

The font belongings is a autograph property for setting several other properties at once. Past using it, you can shorten your style sheets and set values on all properties it replaces. If you choose to use the expanded version, you would have to set all of these to supersede the example above:

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

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

UL { font-manner: italic }

The font-style belongings volition not alter the font size or the font family, it volition only slant the existing font. When attack the ul chemical element, the li elements within will become slanted, since font-manner is inherited. Here is the effect when practical to the test folio you lot know by at present:

Similarly, the font-weight property is used to change the weight - thickness - of the letters. Y'all tin can farther emphasize the listing items past setting their ancestor to exist bold:

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

Which yields:

The last properties, font-variant and line-height, haven't been widely supported in browsers up to at present and are therefore non as unremarkably 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) space below it. This paragraph, as printed in the volume, has space on the left and (slightly less) on the right. CSS can be used to express how much space there should be effectually unlike kinds of elements.

By default, your browser knows quite a scrap about how to display the dissimilar kinds of elements in HTML. For example, it knows that lists and blockquote elements should be indented to set up them apart from the rest of the text. As a designer, y'all tin build on these settings while at the same time provide your ain refinements. Allow'due south use the blockquote chemical element equally an example. Here's a test document:

<HTML>   <Championship>Fredrick the Great meets Bach</Title>   <BODY>     <P>One evening, just as Fredrick the Great was       getting his flute set, and his musicians       were assembled, an officer brought him a       list of the strangers who had arrived. With       his flute in his manus 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."     </BLOCKQUOTE>     <P>The flute was now laid aside, and old Bach, who       had alighted at his son's lodgings, was immediately       summoned to the Palace.   </BODY> </HTML>

The screen-shot beneath is how a typical HTML browser would brandish the document:

Equally you can see, the browser has added space on all sides of the quoted text. In CSS, this infinite is called "margins" and all elements have margins on all four sides. The properties are called: margin-top, margin-right, margin-bottom, and margin-left. You can change how the blockquote element is displayed by writing a little style sheet:

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

The "em" unit of measurement will exist treated in detail in the next affiliate, simply we can already now reveal its secret: it scales relative to the font size. Then, the to a higher place case will result in the vertical margins beingness as high as the font size (1em) of the blockquote, and horizontal margins having nix width. To make sure the quoted text tin can even so be distinguished, it has been given an italic camber. The issue is:

Just like font is a shorthand property to set several font-related backdrop at one time, margin is a autograph property which sets all margin properties. The above example can therefore exist written:

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

The first part of the value - 1em - is assigned to margin-acme. From there it's clockwise: 0em is assigned to margin-correct, 1em is assigned to margin-bottom, and 0em is assigned to margin-left.

With the left margin set to null, the quoted text needs more styling to set it autonomously from the rest of the text. Setting font-style to italic helps, and calculation a background color further amplifies the quote:

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

The result is:

Equally expected, the background color behind the quote has changed. Different previous examples, the color was specified in red/dark-green/bluish (RGB) components. RGB colors are described in item in Chapter  eleven .

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

BLOCKQUOTE {   margin: 1em 0em 1em 0em;   font-style: 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 simply given one value (0.5em). Merely similar the margin property, padding could have taken 4 values which would have been assigned to the peak, correct, bottom and left padding respectively. However, when the aforementioned value is to be set up on all sides, listing information technology one time 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 make it easier for users to scan in hypertext documents, the links should have a style that distinguishes them from normal text. HTML browsers accept oftentimes underlined hyperlink text. Also, various color schemes have been used to indicate if the user has previously visited the link or not. Since hyperlinks are such a key part of the Web, CSS has special support for styling them. Hither's a uncomplicated case:

A:link { text-decoration: underline }

The higher up instance specifies that unvisited links should be underlined:

The links are underlined, every bit we have specified, but they are also blue, which nosotros accept not. When authors do not specify all possible styles, browsers employ default styles to fill in the gaps. The interaction between author styles, browser default styles and user styles (the user's own preferences) is ­another example of CSS's conflict resolution rules. Information technology is called the cascade (the "C" of CSS). Nosotros volition discuss the cascade below.

The selector (A:link) deserves special mentioning. You probably ­recognize "A" as being an HTML element, simply the concluding part is new. ":link" is one of several so-called pseudo-classes in CSS. Pseudo-classes are used to give style to elements based on information exterior of the document itself. For example, the author of the certificate tin't know if a certain link will exist visited or non. Pseudo-classes are described in particular in Chapter  iv , and we'll but give a few more examples here:

A:visited { text-ornamentation: none }

This rule gives style to visited links, only like A:link gave way to unvisited links. Here is a slightly more than complex instance:

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

The terminal dominion introduces a new pseudo-course :hover. Assuming the user is moving a pointing device (similar a mouse), the specified mode volition be applied to the element when the user moves the pointer over ("hovers" over) the link. A common effect is to change the background color. Here is what information technology looks like:

The :hover pseudo-form has an interesting history. It was introduced in CSS2 later on the hover effect became pop amid JavaScript programmers. The JavaScript solution requires complicated lawmaking compared to the CSS pseudo-course and this is an instance of CSS picking upwards effects that have become popular among Spider web designers.

A word near Cascading

A fundamental feature of CSS is that more than than one style sheet tin can influence the presentation of a certificate. This feature is known every bit cascading because the different style sheets are thought of equally coming in a series. Cascading is a key feature of CSS, because we realized that any single document could very probable end up with style sheets from multiple sources: the browser, the designer, and possibly the user.

In the last set of examples you saw that the text color of the links turned blue without that beingness specified in the mode sheet. Also, the browser knew how to format blockquote and h1 elements without being told so explicitly. Everything that the browser knows about formatting is stored in the browser'due south default fashion sheet and is merged with author and user mode sheets when the certificate is displayed.

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

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

How Do You Add A Background Color For All

Elements?,

Source: https://www.w3.org/Style/LieBos2e/enter/

Posted by: joneslessed.blogspot.com

0 Response to "How Do You Add A Background Color For All <h1> Elements?"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel