Chapter 4.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
Chapter 4 CSS 1: Selectors and Basic Styling In this chapter you will learn... The rationale for CSS The syntax of CSS Where CSS styles can be located The different types of CSS selectors What the CSS cascade is and how it works The CSS box model CSS text...
Chapter 4 CSS 1: Selectors and Basic Styling In this chapter you will learn... The rationale for CSS The syntax of CSS Where CSS styles can be located The different types of CSS selectors What the CSS cascade is and how it works The CSS box model CSS text styling What Is CSS? CSS is a W3C standard for describing the appearance of HTML elements. With CSS, we can assign font properties, colors, sizes, borders, background images, positioning and even animate elements on the page. CSS can be added directly to any HTML element (via the style attribute), within the element, or, most commonly, in a separate text file that contains only CSS. Benefits of CSS Improved control over formatting. Improved site maintainability. All formatting can be centralized into one CSS file Improved accessibility. By keeping presentation out of the HTML, screen readers and other accessibility tools work better. Improved page-download speed. Each individual HTML file will contain less style information and markup, and thus be smaller. Improved output flexibility. CSS can be used to adopt a page for different output media. This approach to CSS page design is often referred to as responsive design. CSS allows Responsive Design CSS Versions Style sheets as a way to visually format markup predate the web. W3C decided to adopt CSS, and by the end of 1996, the CSS Level 1 Recommendation was published A year later, the CSS2 was published CSS2.1, did not become an official W3C Recommendation until June 2011 At the same time the CSS2.1 standard was being worked on, a different group at the W3C was working on a CSS3 draft Browser Adoption Perhaps the most important thing to keep in mind with CSS is that the different browsers have not always kept up with the W3C. For this reason, CSS has a reputation for being a somewhat frustrating language. In this book, we hope to redress that negative reputation by covering CSS basics and then incrementally introducing ideas until finally we cover modern frameworks that address many of those challenges. CSS Syntax A CSS document consists of one or more style rules. A rule consists of a selector that identifies the HTML element or elements that will be affected, followed by a series of property:value pairs called the declaration The series of declarations is also called the declaration block. CSS Syntax: Selector Every CSS rule begins with a selector. The selector identifies which element or elements in the HTML document will be affected by the declarations in the rule. CSS Syntax: Properties Each individual CSS declaration must contain a property The CSS2.1 recommendation defines over a hundred different property names! CSS Syntax: Values Each individual CSS declaration must also contain a value The unit of any given value is dependent upon the property. Some property values are from a predefined list of keywords. Others are values such as length measurements, percentages, numbers without units, color values, and URLs. TABLE 4.2 Color Values Method Description Example Name Use one of 17 standard color names. CSS3 has color: red; 140 standard names. color: hotpink; RGB Uses three different numbers between 0 and color: rgb(255,0,0); 255 to describe the red, green, and blue values color: rgb(255,105,180); of the color. Hexadecimal Uses a six-digit hexadecimal number to color: #FF0000; describe the red, green, and blue value of the color: #FF69B4; color RGBa This defines a partially transparent background color: rgba(255,0,0,0.5); color. The “a” stands for “alpha,” which is a term used to identify a transparency HSL Allows you to specify a color using Hue color: hsl(0,100%,100%); Saturation and Light values. This is available color: hsla(330,59%,100%,0.5); only in CSS3. HSLA is also available as well. Common Units of Measure Values Units of measure in CSS are either relative units, in that they are based on the value of something else, or absolute units, in that they have a real-world size. Some example measures (See Table 4.3 for more) px Pixel. In CSS2 this is a relative measure, while in CSS3 it is absolute (1/96 of an inch) em Equal to the computed value of the font-size property of the element on which it is used. % A measure that is always relative to another value. in Inches cm Centimeters CSS Comments NOTE It is helpful to add comments to your style sheets. Comments take the form: It is a common practice to locate related style rules together, and then indicate that they are related via a comment. For instance: nav#main { … } nav#main ul { … } nav#main ul li { … } header { … } h1 { … } Comments can also be a helpful way to temporarily hide any number of rules, to help with debugging. Location of Styles CSS style rules can be located in three different locations. Inline Styles Embedded Style Sheet External Style Sheet These three are not mutually exclusive, in that you could place your style rules in all three. Inline Styles Inline styles are style rules placed within an HTML element via the style attribute Share Your Travels An inline style only affects Description the element it is defined... Reviews within and overrides any LISTING Inline styles example other style definitions for properties used Notice that a selector is not necessary Embedded Style Sheet Embedded style sheets (also called internal styles) are style rules placed Chapter 4 within the element (inside the h1 { font-size: 24pt; } element of an HTML h2 { document) font-size: 18pt; font-weight: bold; While better than inline styles, } using embedded styles is also by and large discouraged. LISTING Embedded styles example External Style Sheet External style sheets are style rules placed within an external text file with the.css extension. When you change an external style sheet, all HTML documents that Chapter 4 reference that style sheet will automatically use the updated version. The browser is able to cache the LISTING Referencing an external style sheet external style sheet, which can improve performance as well. Selectors When defining CSS rules, you will need to use a selector. Selectors tell the browser which elements will be affected by the property values Selectors allow you to select individual or multiple HTML elements. Three basic selector types have been around since the earliest CSS2 specification. – Element Selectors – Class Selectors – Id Selectors The Document Object Model (DOM) NOTE The Document Object Model (DOM) is how a browser represents an HTML page internally. This DOM is akin to a tree representing the overall hierarchical structure of the document. In the last chapter, we learned some of the familial terminologies (such as descendants, ancestors, siblings, etc.) in an HTML document. You will at times have to think about the elements in your HTML document in terms of their position within the hierarchy. Element Selectors p, div, aside { margin: 0; Element selectors select all instances padding: 0; } of a given HTML element. You can also select all elements by p{ using the universal element selector margin: 0; padding: 0; (*) } div { You can select a group of elements by margin: 0; separating the different element names padding: 0; } with commas. aside { margin: 0; padding: 0; } LISTING Sample grouped selector Class and ID Selectors A class selector allows you to An ID selector allows you to target a simultaneously target different HTML specific element by its id attribute elements regardless of their position in regardless of its type or position in the the document tree. document tree. HTML elements labeled with the same HTML elements labeled with an id class attribute value, can be targeted for attribute, can be targeted for styling by styling by using a class selector, which using an id selector, which takes the takes the form: form: period (.) followed by the class name. pound/hash (#) followed by the id name. Class and ID Selector Example Consider Figure 4.4. The original HTML can be modified to add class and id values, which are then styled in CSS. Id selector #first matches the div with id “first” Class selectors.orange and.circle, match all divs with those class values. Notice that an element can be tagged with multiple classes. Attribute Selectors An attribute selector provides a way to select HTML elements either by the presence of an element attribute or by the value of an attribute. Attribute selectors can be helpful in the styling of hyperlinks and form elements (which come up in the next chapter) These selectors can be combined with the element id and class selectors. You use square brackets to create attribute selectors () TABLE 4.4 Attribute Selectors Matches Example [] A specific attribute. [title] Matches any element with a title attribute [=] A specific attribute with a specific a[title="posts from this country"] value. Matches any element whose title attribute is exactly “posts from this country” [~=] A specific attribute whose value [title~="Countries"] matches at least one of the words in a Matches any title attribute that contains the word “Countries“ space-delimited list of words. [^=] A specific attribute whose value begins a[href^="mailto"] with a specified value. Matches any element whose href attribute begins with “mailto“ [*=] A specific attribute whose value img[src*="flag"] contains a substring. Matches any element whose src attribute contains somewhere within it the text “flag“ [$=] A specific attribute whose value ends a[href$=".pdf"] with a specified value. Matches any element whose href attribute ends with the text “.pdf“ Attribute Selector Example Here we show an attribute selector style links to show PDF files differently than other links () Pseudo-Element and Pseudo-Class Selectors A pseudo-element selector is a way to select something that does not exist explicitly as an element in the HTML document tree. You can select the first line or first letter of any HTML element using a pseudo-element selector. A pseudo-class selector targets either a particular state or a variety of family relationships This type of selector is for targeting link states and for adding hover styling for other elements Common Pseudo-Class and Pseudo-Element Selectors a:link Selects links that have not been visited. a:visited Selects links that have been visited. :hover Selects elements that the mouse pointer is currently above. :active Selects an element that is being activated by the user. A typical example is a link that is being clicked. :first-child Selects an element that is the first child of its parent. :first-letter Selects the first letter of an element. :first-line Selects the first line of an element. Table 4.5 for more common selectors. Styling a link using pseudo-class selectors Syntax of a descendant selection Contextual Selectors A contextual selector (in CSS3 also called combinators) allows you to select elements based on their ancestors, descendants, or siblings. A descendant selector matches all elements that are contained within another element. The character used to indicate descendant selection is a space “ “ A child selector matches a specified element that is a direct child of the specified element. The character used is a “>” An Adjacent selector matches a specified element that is the next sibling of the specified element. The character used is a “+” A General selector matches All following elements that shares the same parent as the specified element. The character used is a “~” Contextual selectors in action The Cascade: How Styles Interact The “Cascade” in CSS refers to how conflicting rules are handled. CSS uses the following cascade principles to help it deal with conflicts: inheritance, specificity, and location. The Cascade: Inheritance Inheritance is the principle that many CSS properties affect their descendants as well as themselves. Font, color, list, and text properties (from Table 4.1) are inheritable; Layout, sizing, border, background, and spacing properties are not. it is also possible to inherit properties that are normally not inheritable using inherit The Cascade: Specificity Specificity is how the browser determines which style rule takes precedence when more than one style rule could be applied. The more specific selector takes precedence Class selectors take precedence over element selectors, and id selectors take precedence over class selectors Note: In figure color and font-weight properties are overridden by the more specific and selectors. Simplified Specificity algorithm The Cascade: Location Finally, when inheritance and specificity cannot determine style precedence, the principle of location will be used. When rules have the same specificity, then the latest are given more weight. For instance, an inline style will override one defined in an external author style sheet or an embedded style sheet. The Box Model In CSS, all HTML elements exist within an element box. In order to become proficient with CSS, you must become familiar with the box model. Block Elements Block-level elements such as , , , , and are each contained on their own line. without styling, two block-level elements can’t exist on the same line Block-level elements use the normal CSS box model Inline Elements Inline elements do not form their own blocks but instead are displayed within lines. Normal text in an HTML document is inline, as are elements such as , , , and. When there isn’t enough space left on the line, the content moves to a new line Inline Element Example Block and inline elements together Background The background of an element fills an element out to its border Background image properties include: Background, background-attachment, background-color, background-image, background-origin, background-position, background-repeat, background-size Some of these properties work together, others do not. Background image examples Border and Shadow Examples Margins and Padding Margins add spacing around an element’s content Padding adds spacing within elements. Borders divide the margin area from the padding area. Collapsing margins The W3C defines collapsing margins as: In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin. What this means is that when the vertical margins of two elements touch, only the largest margin value of the elements will be displayed Horizontal margins, on the other hand, never collapse. Box Model: All or one NOTE With border, margin, and padding properties, it is possible to set the properties for one or more sides in a single property, or individually border-top-color: red; border-right-color: green; border-bottom-color: yellow; border-left-color: blue; Alternately, we can set all four sides to a single value via: border-color: red; Or we can set all four sides to different values via: border-color: red green orange blue; Another shortcut is to use just two values; in this case the first value sets top and bottom, while the second sets the right and left. border-color: red yellow; Box Dimensions Block-level elements have width and height properties. They also have a min-width, min-height, max-width, and max-height properties as well to help when the width or a height might be specified as a % of its parent container Since the width and the height only refer to the size of the content area, the total size of an element is equal to the size of its content area plus the sum of its padding, borders, and margins. The border-box approach To reduce complexity of adding margins, content and borders, you can use the newer border-box approach that is more intuitive. Overflow Proprerty It is possible to control what happens with the content if the box’s width and height are not large enough to display the content using the overflow property Box sizing via percent CSS Text Styling CSS provides two types of properties that affect text. Font properties that affect the font and its appearance. Paragraph properties that affect the text in a similar way no matter which font is being used Many of the most common font properties are shown in Table 4.9 and include – Font, font-family, font-style, font-size, font-variant, font-weight Font Family Just because a given font is available on the web developer’s computer does not mean it will be available for all users. For this reason, it is conventional to supply a so-called web font stack— a series of alternate fonts to use in case the original font choice is not on the user’s computer Different font families Font Sizes If we wish to create web layouts that work well on different devices, we should learn to use relative units such as em units or percentages for our font sizes it can quickly become difficult to calculate actual sizes when there are nested elements – For this reason, CSS3 now supports a new relative measure, the rem (for root em unit). This unit is always relative to the size of the root element (i.e., the element). To muddy the picture even more, some developers have begun to advocate again for using the pixel as the unit of measure in CSS since modern browsers provide built-in scaling/zooming that preserve layout… @font-face DIVE DEEPER The @font-face selector that allows you to use a font even if it is not installed on the user’s computer. Open source font sites such as Google Web Fonts (https://fonts.google.com) and Font Squirrel (http://www.fontsquirrel.com/) have promoted the use of @font-face To use Droid Sans, you can add the following to your section Or, add the following import inside one of your CSS files: @import url(https://fonts.googleapis.com/css?family=Droid+Sans); Or check out the longer-form @font-face selector () Font Weight Google Fonts made web fonts available to the masses, before that font-weight was typically set to either normal or bold For instance, the popular Open Sans font has five different weights: light, regular, semi-bold, bold, and extra bold Within your CSS you specify which of these weights by using their numeric value, which typically ranges from 100 and 900, with larger numbers bolder than lower numbers Paragraph Properties Just as there are properties that affect the font in CSS, there is also a range of CSS properties that affect text independently of the font. Table 2.10 describes the following paragraph properties in detail: letter- spacing, line-height, list-style-image, list-style-type, text-align, text- decoration, text-direction, text-intent, text-shadow, text-transform, vertical-align and word-spacing Sample text properties CSS Frameworks and Variables This chapter and the exercises should make you reasonably confident about the CSS box model and text formatting Chapter 5 covers the CSS for working with forms and tables Chapter 7 covers layout, transitions, and animations as well If you are not feeling overwhelmed yet by CSS, you might be by the end of Chapter 7. – as an alternative to mastering CSS and getting an acceptable visual design, some developers instead use an already developed CSS framework What is a CSS Framework? A CSS framework is a set of CSS classes or other software tools that make it easier to use and work with CSS. Early CSS frameworks became popular chiefly as a way to more easily create complex grid-based layouts More sophisticated subsequent CSS Frameworks such as – Bootstrap (https://getbootstrap.com/) and – Foundation (https://get.foundation/) provide much more than a grid system; they provide a comprehensive set of predefined CSS classes, which makes it easier to construct a consistent and attractive web interface. Table 4.11 lists even more popular CSS Frameworks Examples using Frameworks CSS Variables CSS Variables (also called custom properties) are a new feature that let you define variables (which must begin with a double hyphen) at the top of your CSS file usually within a special :root pseudo-class selector, and reference those variables as property values using the var() CSS function. Duplication of colors, spacing, and borders, often happens numerous times within a single file (and rightly so). CSS variables address this issue without using a preprocessor (Chapter 7). Example Part 1 (duplicate values) header { #results { background-color: #431c5d; background-color: #431c5d; color: #e05915; font-size: 18px; padding: 4px; border-radius: 5px; box-shadow: 6px 5px 20px 1px rgba(0,0,0,0.22); padding: 4px; margin: 0; box-shadow: 6px 5px 20px 1px rgba(0,0,0,0.22); } } header button { background-color: #e05915; border-radius: 5px; border-color: #e6e9f0; padding: 4px; color: #e6e9f0; font-size: 18px; margin-top: 9px; } LISTING 4.8 Duplicate property values in CSS Example Part 2 (CSS variables) :root { header button { --bg-color-main: #431c5d; background-color: var(--bg-color-secondary); --bg-color-secondary: #e05915; border-radius: var(--radius-boxes); --fg-color-main: #e6e9f0; border-color: var(--fg-color-main); --radius-boxes: 5px; padding: var(--padding-boxes); --padding-boxes: 4px; color: var(--fg-color-main); --fontsize-default: 18px; font-size: var(--fontsize-default); --shadow-color: rgba(0,0,0,0.22); margin-top: calc( --fontsize-default / 2 ); --dropshadow: 6px 5px 20px 1px var(--shadow-color); } } #results { header { background-color: var(--bg-color-main); background-color: var(--bg-color-main); font-size: var(--fontsize-default:); color: var(--bg-color-secondary); border-radius: var(--radius-boxes); padding: var(--padding-boxes); padding: var(--padding-boxes); box-shadow: var(--dropshadow); box-shadow: var(--dropshadow); margin: 0; } } LISTING 4.9 Using CSS Variables Key Terms absolute units combinators element box location responsive design attribute selector contextual selector element selectors margin selector author-created style CSS em units Padding specificity sheets CSS framework embedded style percentages style rules block-level elements sheets CSS variable property universal element box model external style sheets CSS3 modules property:value pair selector browser style sheets generic font Declaration pseudo-class selector user style sheets cascade grouped selector declaration block pseudo-element vendor prefixes Cascading Style id selector selector Sheets descendant selector web font stack inheritance relative units class selector Document Object x-height inline styles rem collapsing margins Model Copyright This work is protected by United States copyright laws and is provided solely for the use of instructors in teaching their courses and assessing student learning. Dissemination or sale of any part of this work (including on the World Wide Web) will destroy the integrity of the work and is not permitted. The work and materials from it should never be made available to students except by instructors using the accompanying text in their classes. All recipients of this work are expected to abide by these restrictions and to honor the intended pedagogical purposes and the needs of other instructors who rely on these materials.