Читать книгу HTML5, JavaScript, and jQuery 24-Hour Trainer - Cameron Dane - Страница 18

Part I
HTML and CSS
Lesson 4
Introduction to CSS

Оглавление

The first three lessons of the book introduced you to a large number of tags, but it has so far not been possible to style the presentation of these tags when they appear onscreen. As mentioned, HTML5 has removed most of the remaining presentation-based tags and attributes, and presentation and style are instead the responsibility of another technology called Cascading Style Sheets (CSS).

The main reason for this is a concept called “separation of concerns.” The HTML markup language is responsible for providing the content of the page, while CSS is responsible for the presentation and styling of this content. This means it is possible to change either without affecting the other.

For instance, it is usually possible to completely restyle an existing web page without changing the HTML at all. Additionally, it is possible to change the content of a web page without needing to change the CSS at all.

This lesson will introduce the fundamentals of CSS, and will mainly focus on the way individual elements can be styled. In the next lesson, you will consolidate this knowledge, and also look at how CSS behaves when elements interact with one another.

The HTML5 specification includes a companion specification called CSS3 – version 3 of Cascading Style Sheets – that greatly enhances the power of CSS. You will look in-depth at CSS3 later in the book, but for the next two lessons you will focus on the fundamentals of CSS.

Note

The capabilities of CSS are truly astounding, so this lesson will not introduce you to everything CSS can do. The aim of this lesson is instead to provide you with a sound understanding of the fundamentals: once these are understood it is easy to find information about specific features.

CSS Selectors

In this section, you will get started with CSS by styling the web page developed in Lesson 2. This page utilized header and paragraph elements to format text, and also included images and hyperlinks. Ensure you have the following HTML available to work with in this section:


As you will see, CSS can be included in a web page in three different ways. This section will focus on a single approach: adding CSS within a style element in the head of the web page.

In order to apply a style to an element, you first need a way of selecting the elements that you wish to style. CSS provides four key selection mechanisms, the most simple of which is to select the elements based on their tag name. For instance, if you wanted to select all the h1 elements in the document and display them in a red font, you could add the following to the head section:


If you refresh the web page, the top header will display in red.

Note

A number of colors can be referenced directly by name, but it is more common to represent colors as a string such as #FF0000. This is a hash, followed by three sets of hexadecimal numbers specifying the ratio of red, green, and blue respectively. There are many resources online for finding colors using this format, and you will see many examples throughout this book.

This simple example demonstrates most of what you need to know about the syntax of CSS. You start by specifying the selector: h1 in this case. Next, you place a set of stylistic properties between curly brackets where each stylistic property is in the form of a name/value pair. In this case, the name of the property is color (technically this is foreground color), while the value is red. A colon separates the name and value, and the whole construct is concluded with a semicolon. I will refer to this entire construct as a CSS rule.

It is possible to add multiple stylistic properties to the same selection. The following rule also specifies the font-family and the fact that the text should be underlined.


Figure 4.1 shows the result.


Figure 4.1


The font-family property has a more interesting value than color. Many fonts are proprietary; therefore, you cannot be sure which fonts the user's browser will provide. The value of the property therefore contains a list of fonts in priority order. In this case, the value states:

● Try to use Arial if it is available.

● If that is not available use Helvetica.

● If that is not available use any sans-serif font.

Imagine now that you want this style to apply to all the headings in the web page. Obviously, you could duplicate this rule three times and select h1, h2 and h3 in three separate rules. You always want to avoid duplication if you can, however, because it leads to maintenance issues.

There are, in fact, two ways you can achieve this without duplication. The first is by specifying the three different tags separated by a comma:


A more elegant solution, however, is to use classes. Any element can be assigned one or more classes with the class attribute. A class is just an arbitrary name you choose and usually describes some aspect that a set of elements have in common. For example:


In this case, redHeader is the class name. It is then possible to style all elements with this class using the following selector:


Notice the dot at the start of the selector: This always implies that you are selecting elements by a class. If you redisplay the web page, all three headers will display with the specified properties.

If you want to assign two classes to an element, the class names are separated by a space. For example:


You can then select elements based on either of these classes.

Another common way to select elements is by their id. Any element can be given an id, but, unlike classes, IDs must be unique within a document. The following is an example of a paragraph with an id:


It is then possible to create a CSS rule that selects this element as follows:


Notice that the selector begins with a # to indicate it is based on id. This particular example will display the paragraph with the matching id in bold.

The final common way to select elements is via pseudo-classes. These allow you to select elements based on features that cannot be expressed by the other selectors, for instance, every even numbered row in a table.

If you consider the firstParagraph example, you may notice that there is a potential issue lurking here. If a new paragraph is added before the current first paragraph, you would need to remember to swap the id onto this element – which would be easy to forget. A better option is to state that you want the first paragraph to be in bold, without specifying which paragraph is the first in the document. This can be achieved as follows:


This selector first selects all the p elements, and then limits this selection to just the first element found of its type. Because all the elements returned have the type of p, the first-of-type selector will return the first p element in the document. Pseudo-class selectors always begin with a single or double colon.

Pseudo-classes are also useful for providing styles to elements based on their state. For instance, if you wanted links to turn green when the user hovered over them, you could use the following selector:


There is no way to perform this selection without pseudo-classes.

Note

CSS actually supports two related, but technically distinct, mechanisms: pseudo-classes and pseudo-elements. Technically, the selectors you have looked at are pseudo-classes because they select elements that you could not select via other selectors. CSS also supports pseudo-elements: These allow a portion of an element to be selected, such as the first letter in a paragraph, or the first line in a paragraph.

Pseudo-element selectors are supposed to use a double colon rather than a single colon, but some browsers do not support the double colon syntax, so the single colon syntax is regularly used for both types of selector.

When selecting the first paragraph in the document, you are actually combining two types of selector: an element selector and a pseudo-class selector. It turns out that you can combine selectors in many interesting ways.

For example, if I wanted to select all the h1 elements that had the class redParagraph, I could use the following selector:


Notice that there is no space between the element selector and the class selector. Alternatively, if I wanted to select all h1 elements that had both the redHeader and pageHeader classes, I could use the following:


Alternatively, you can select elements only when they are children of elements returned by other selections. For instance, you can specify that the cite element should be capitalized, but only when it is a child of a blockquote element (which, as it happens, it always is):


Notice in this case there is a space between the two selections. This will match cite elements if they are a descendant of a blockquote element, even if blockquote is not their immediate parent. Another way to think about this is two distinct selections. CSS first selects all the blockquote elements, and then it searches for any cite elements that are descendants.

With the > operator, it is possible to specify that the selection should only occur if the element is an immediate child of the first selection:


CSS Files and Inline Styles

So far, you have used the style element to add CSS to a web page. Although this is an easy way of adding CSS, it has the disadvantage that you cannot use the same CSS across multiple pages.

It is therefore far more common to place all the CSS in a file with a .css extension and link it to each web page that needs to use it. In order to try this out, save the styles you have added so far in a file called examples.css. Place this in the same folder as the HTML page, but do not include the style element.

Now, remove the whole style element from the head of the document, and replace it with the following:


Again, the href attribute is using a relative URL to load the style sheet, but it could also use an absolute URL. If you reload the web page it should display the same as before.

An alternative way of specifying CSS properties is via the style attribute on individual elements. Although this approach is generally discouraged, it can be useful when a style is unique to a single element. As you will also see, these styles have a higher precedence, so it can be a useful approach for overriding global styles. The following is an example:


Notice that the inline styles use the same basic syntax: Colons separate names and properties, and semicolons separate styles. Obviously, they do not include a selector because they are applied to the element they are declared on.

Specificity

The same element may match multiple CSS rules. When this occurs, all the properties defined in all the rules are applied to the element. You have already seen an example of this with the h1 element.


Конец ознакомительного фрагмента. Купить книгу
HTML5, JavaScript, and jQuery 24-Hour Trainer

Подняться наверх