CSS 1: Selectors and Basic Styling PDF
Document Details
Uploaded by BuoyantSnake7269
Birzeit University
Tags
Summary
This document covers CSS, Cascading Style Sheets, used for web page presentation. It discusses the rationale for using CSS, its syntax, and the benefits of using it over HTML alone, including improved control, maintainability, accessibility, and download speeds.
Full Transcript
4 CSS 1: Selectors and Basic Styling C H AP TER O BJ ECTIVES 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 Wh...
4 CSS 1: Selectors and Basic Styling C H AP TER O BJ ECTIVES 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 T his chapter provides a substantial introduction to CSS (Cascading Style Sheets), the principal mechanism for web authors to modify the visual presentation of their web pages. Just as with HTML, there are many books and websites devoted to CSS.1–4 While simple styling is quite straightforward, more advanced CSS tasks such as layout and positioning can be quite complicated, which is why we’ve put those items in the next chapter. Since this book covers CSS in just two chapters, it cannot possibly cover all of it. Instead, our intent in this chapter is to cover the foundations necessary for working with contemporary CSS; Chapter 7 will cover CSS layout and positioning. 122 4.1 What Is CSS? 123 4.1 What Is CSS? At various places in the previous chapter on HTML, it was mentioned that in cur- rent web development best practices, HTML should not describe the formatting or presentation of documents. Instead that presentation task is best performed using Cascading Style Sheets (CSS). CSS is a W3C standard for describing the appearance of HTML elements. Another common way to describe CSS’s function is to say that CSS is used to define the presentation of HTML documents. 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. 4.1.1 Benefits of CSS Before digging into the syntax of CSS, we should say a few words about why using CSS is a better way of describing appearances than HTML alone. The benefits of CSS include the following: Improved control over formatting. The degree of formatting control in CSS is significantly better than that provided in HTML. CSS gives web authors fine- grained control over the appearance of their web content. Improved site maintainability. Websites become significantly more maintain- able because all formatting can be centralized into one CSS file, or a small handful of them. This allows you to make site-wide visual modifications by changing a single file. Improved accessibility. CSS-driven sites are more accessible. By keeping pre- sentation out of the HTML, screen readers and other accessibility tools work better, thereby providing a significantly enriched experience for those reliant on accessibility tools. Improved page-download speed. A site built using a centralized set of CSS files for all presentation will also be quicker to download because 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. Figure 4.1 illustrates a site that responds to different browser and window sizes. 4.1.2 CSS Versions Just like with the previous chapter, we should say a few words about the history of CSS. Style sheets as a way to visually format markup predate the web. In the early 124 CHAPTER 4 CSS 1: Selectors and Basic Styling FIGURE 4.1 CSS-based responsive design (site by Peerapong Pulpipatnan on ThemeForest.net) 1990s, a variety of different style sheet standards were proposed, including JavaScript style sheets, which was proposed by Netscape in 1996. Netscape’s proposal was one that required the use of JavaScript programming to perform style changes. Thankfully for nonprogrammers everywhere, the W3C decided to adopt CSS, and by the end of 1996, the CSS Level 1 Recommendation was published. A year later, the CSS Level 2 Recommendation (also more succinctly labeled simply as CSS2) was published. Even though work began over a decade ago, an updated version of the Level 2 Recommendation, CSS2.1, did not become an official W3C Recommendation until June 2011. And to complicate matters even more, all through the last decade (and to the present day as well), during the same time the CSS2.1 standard was being worked on, a different group at the W3C was working on a CSS3 draft. To make CSS3 more manageable for both browser manufacturers and web designers, the W3C subdivided it into a variety of different CSS3 modules. Some of the CSS3 modules that have made it to the Recommendation stage include CSS Selectors, CSS Namespaces, CSS Media Queries, CSS Color, CSS Fonts, CSS Basic UI, CSS Grids, and CSS Style Attributes. 4.1.3 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. While Microsoft’s Internet Explorer was an early champion of CSS (its IE3, released in 1996, was the first major browser to support CSS, and its IE5 for the Macintosh was the first browser to reach almost 100 percent CSS1 support in 2000), its later versions (especially IE5, IE6, and IE7) for Windows had uneven support for certain parts of CSS2. However, not all browsers have implemented parts of the CSS2 Recommendation. For this reason, CSS has a reputation for being a somewhat frustrating lan- guage. Based on over a decade of experience teaching university students CSS, this reputation is well deserved. Since CSS was designed to be a styling language, text styling is quite easy. However, CSS was not really designed to be a layout language, so authors often find it tricky dealing with floating elements, relative positions, 4.2 CSS Syntax 125 inconsistent height handling, overlapping margins, and nonintuitive naming (we’re looking at you, relative and !important). When one adds in the uneven CSS 2.1 support (prior to IE8 and Firefox 2) in browsers for CSS2.1, it becomes quite clear why many software developers developed a certain fear and loathing of CSS. 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. 4.2 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 (each pair is also called a declaration), as shown in Figure 4.2. The series of declarations is also called the declaration block. As one can see in the illustration, a declaration block can be together on a single line or spread across multiple lines. The browser ignores white space (i.e., spaces, tabs, and returns) between your CSS rules so you can format the CSS however you want. Notice that each declaration is terminated with a semicolon. The semicolon for the last declara- tion in a block is in fact optional. However, it is sensible practice to also terminate the last declaration with a semicolon as well; that way, if you add rules to the end later, you will reduce the chance of introducing a rather subtle and hard-to-discover bug. declaration selector { property: value; property2: value2; } rule syntax declaration block selector em { color: red; } property value examples p { margin: 5px 0 10px 0; font-weight: bold; font-family: Arial, Helvetica, sans-serif; } FIGURE 4.2 CSS syntax 126 CHAPTER 4 CSS 1: Selectors and Basic Styling 4.2.1 Selectors Every CSS rule begins with a selector. The selector identifies which element or ele- ments in the HTML document will be affected by the declarations in the rule. Another way of thinking of selectors is that they are a pattern that is used by the browser to select the HTML elements that will receive the style. As you will see later in this chapter, there are a variety of ways to write selectors. 4.2.2 Properties Each individual CSS declaration must contain a property. These property names are predefined by the CSS standard. The CSS2.1 recommendation defines over a hun- dred different property names, so some type of reference guide, whether in a book, online, or within your web development software, can be helpful.5 This chapter and the next one on CSS (Chapter 7) will only be able to cover most of the common CSS properties. Table 4.1 lists many of the most commonly used CSS properties. Properties marked with an asterisk contain multiple subproperties not listed here (e.g., border-top, border-top-color, border-top-width, etc.). Property Type Property Fonts font font-family font-size font-style font-weight @font-face Text letter-spacing line-height text-align text-decoration* text-indent Color and background background background-color background-image background-position background-repeat box-shadow color opacity Borders border* border-color border-width border-style border-top, border-left,...* border-image* border-radius (continued) 4.2 CSS Syntax 127 Property Type Property Spacing padding padding-bottom, padding-left,... margin margin-bottom, margin-left,... Sizing height max-height max-width min-height min-width width Layout bottom, left, right, top clear display float overflow position visibility z-index Lists list-style* list-style-image list-style-type Effects animation* filter perspective transform* transition* TABLE 4.1 Common CSS Properties 4.2.3 Values Each CSS declaration also contains a value for a property. 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, num- bers without units, color values, and URLs. Colors would seem at first glance to be the clearest of these units. But as we will see in more detail in Chapter 6, color can be a complicated thing to describe. CSS supports a variety of different ways of describing color; Table 4.2 lists the different ways you can describe a color value in CSS. Just as there are multiple ways of specifying color in CSS, so too there are mul- tiple ways of specifying a unit of measurement. As we will see later in Section 4.7, these units can sometimes be complicated to work with. When working with print 128 CHAPTER 4 CSS 1: Selectors and Basic Styling 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; each of the three RGB values is between 0 and FF (which is 255 in decimal). Notice that the hexadecimal number is preceded by a hash or pound symbol (#). 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 that is a value between 0.0 (fully transparent) and 1.0 (fully opaque). 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. TABLE 4.2 Color Values design, we generally make use of straightforward absolute units such as inches or centimeters and picas or points. However, because different devices have differing physical sizes as well as different pixel resolutions and because the user is able to change the browser size or its zoom mode, these absolute units don’t always make sense with web element measures. Table 4.3 lists the different units of measure in CSS. Some of these are relative units, in that they are based on the value of something else, such as the size of a Unit Description Type px Pixel. In CSS2 this is a relative measure, while in Relative (CSS2) CSS3 it is absolute (1/96 of an inch). Absolute (CSS3) em Equal to the computed value of the font-size Relative property of the element on which it is used. When used for font sizes, the em unit is in relation to the font size of the parent. (continued) 4.2 CSS Syntax 129 Unit Description Type % A measure that is always relative to another value. Relative The precise meaning of % varies depending upon the property in which it is being used. ex A rarely used relative measure that expresses size Relative in relation to the x-height of an element’s font. ch Another rarely used relative measure; this one Relative expresses size in relation to the width of the zero (CSS3 only) (“0”) character of an element’s font. rem Stands for root em, which is the font size of the Relative root element. Unlike em, which may be different (CSS3 only) for each element, the rem is constant throughout the document. vw, vh Stands for viewport width and viewport height. Relative Both are percentage values (between 0 and 100) (CSS3 only) of the viewport (browser window). This allows an item to change size when the viewport is resized. in Inches Absolute cm Centimeters Absolute mm Millimeters Absolute pt Points (equal to 1/72 of an inch) Absolute pc Pica (equal to 1/6 of an inch) Absolute TABLE 4.3 Common Units of Measure Values NOTE It is often helpful to add comments to your style sheets. Comments take the form: Real-world CSS files can quickly become quite long and complicated. It is a common practice to locate style rules that are related together, and then indicate that they are related via a comment. For instance: nav#main { … } nav#main ul { … } nav#main ul li { … } 130 CHAPTER 4 CSS 1: Selectors and Basic Styling header { … } h1 { … } Comments can also be a helpful way to temporarily hide any number of rules, which can make debugging your CSS just a tiny bit less tedious. parent element. Others are absolute units, in that they have a real-world size. Unless you are defining a style sheet for printing, it is recommended you avoid using abso- lute units. Pixels are perhaps the one popular exception (though, as we shall see later, there are also good reasons for avoiding the pixel unit). In general, most of the CSS that you will see uses either px, em, or % as a measure unit. 4.3 Location of Styles HANDS-ON EXERCISES As mentioned earlier, CSS style rules can be located in three different locations. These three are not mutually exclusive, in that you could place your style rules in LAB 4 Adding Styles all three. In practice, however, web authors tend to place all of their style definitions Embedded Styles in one (or more) external style sheet files. External Styles 4.3.1 Inline Styles Inline styles are style rules placed within an HTML element via the style attri- bute, as shown in Listing 4.1. An inline style only affects the element it is defined within and overrides any other style definitions for properties used in the inline style (more about this below in Section 4.5.2). Notice that a selector is not necessary with inline styles and that semicolons are only required for separating multiple rules. Using inline styles is generally discouraged since they increase bandwidth and decrease maintainability (because presentation and content are intermixed and because it can be difficult to make consistent inline style changes across multiple files). Inline styles can, however, be handy for quickly testing out a style change. Share Your Travels Description... Reviews LISTING 4.1 Inline styles example 4.3 Location of Styles 131 4.3.2 Embedded Style Sheet Embedded style sheets (also called internal styles) are style rules placed within the element (inside the element of an HTML document), as shown in Listing 4.2. While better than inline styles, using embedded styles is also by and large discouraged. Since each HTML document has its own element, it is more difficult to consistently style multiple documents when using embedded styles. Just as with inline styles, embedded styles can, however, be helpful when quickly testing out a style that is used in multiple places within a single HTML document. We sometimes use embedded styles in the book or in lab materials for that reason. Chapter 4 h1 { font-size: 24pt; } h2 { font-size: 18pt; font-weight: bold; }... LISTING 4.2 Embedded styles example 4.3.3 External Style Sheet External style sheets are style rules placed within a external text file with the.css extension. This is by far the most common place to locate style rules because it provides the best maintainability. When you make a change to an external style sheet, all HTML documents that reference that style sheet will automatically use the updated version. The browser is able to cache the external style sheet, which can improve the performance of the site as well. To reference an external style sheet, you must use a element within the element, as shown in Listing 4.3. You can link to several style sheets at a time; each linked style sheet will require its own element. Chapter 4 LISTING 4.3 Referencing an external style sheet 132 CHAPTER 4 CSS 1: Selectors and Basic Styling NOTE There are in fact three different types of style sheets: 1. Author-created style sheets (what you are learning in this chapter) 2. User style sheets 3. Browser style sheets User style sheets allow the individual user to tell the browser to display pages using that individual’s own custom style sheet. This option can usually be found in a browser’s accessibility options. The browser style sheet defines the default styles the browser uses for each HTML element. Some browsers allow you to view this stylesheet. For instance, in Firefox, you can view this default browser style sheet via the following URL: resource://gre-resources/forms.css. The browser stylesheet for WebKit browsers such as Chrome and Safari can be found (for now) at: http://trac.webkit.org/ browser/trunk/Source/WebCore/css/html.css. 4.4 Selectors HANDS-ON EXERCISES As teachers, we often need to be able to relay a message or instruction to either individual students or groups of students in our classrooms. In spoken language, we LAB 4 Id and Class Selectors have a variety of different approaches we can use. We can identify those students by Attribute Selectors saying things like, “All of you talking in the last row,” or “All of you sitting in an Pseudo-Class aisle seat,” or “All of you whose name begins with ‘C,’ ” or “All first-year stu- Selectors dents,” or “John Smith.” Each of these statements identifies or selects a different Contextual Selectors (but possibly overlapping) set of students. Once we have used our student selector, we can then provide some type of message or instruction, such as “Talk more qui- etly,” “Hand in your exams,” or “Stop texting while I am speaking.” In a similar way, when defining CSS rules, you will need to first use a selector to tell the browser which elements will be affected by the property values. CSS selec- tors allow you to select individual or multiple HTML elements. NOTE In the last chapter, Figure 3.5 illustrated some of the familial terminologies (such as descendants, ancestors, siblings, etc.) that are used to describe the relationships between elements in an HTML document. The Document Object Model (DOM) is how a browser represents an HTML page internally. This DOM is akin to a tree represent- ing the overall hierarchical structure of the document. As you progress through these chapters on CSS, you will at times have to think about the elements in your HTML document in terms of their position within the hier- archy. Figure 4.3 illustrates a sample document structure as a hierarchical tree. 4.4 Selectors 133 FIGURE 4.3 Document outline/tree The topic of selectors has become more complicated than it was when we started teaching CSS in the late 1990s. There are now a variety of new selectors that are supported by all modern browsers. Before we get to those, let us look at the three basic selector types that have been around since the earliest CSS2 specification. 4.4.1 Element Selectors Element selectors select all instances of a given HTML element. The example CSS rules in Figure 4.2 illustrate two element selectors. You can also select all elements by using the universal element selector, which is the * (asterisk) character. You can select a group of elements by separating the different element names with commas. This is a sensible way to reduce the size and complexity of your CSS files by combining multiple identical rules into a single rule. An example grouped selector is shown in Listing 4.4, along with its equivalent as three sepa- rate rules. 4.4.2 Class Selectors A class selector allows you to simultaneously target different HTML elements regardless of their position in the document tree. If a series of HTML elements have been labeled with the same class attribute value, then you can target them for styl- ing by using a class selector, which takes the form: period (.) followed by the class name. Figure 4.4 illustrates the use of a class selector. Notice that an element can be tagged with multiple classes. In Figure 4.4, both the orange and circle classes are assigned to the second last element. 134 CHAPTER 4 CSS 1: Selectors and Basic Styling p, div, aside { margin: 0; padding: 0; } p { margin: 0; padding: 0; } div { margin: 0; padding: 0; } aside { margin: 0; padding: 0; } LISTING 4.4 Sample grouped selector PRO TIP Grouped selectors are often used as a way to quickly reset or remove browser defaults. The goal of doing so is to reduce browser inconsistencies with things such as margins, line heights, and font sizes. These reset styles can be placed in their own CSS file (perhaps called reset.css) and linked to the page before any other external style sheets. An example of a simplified reset is shown below: html, body, div, span, h1, h2, h3, h4, h5, h6, p { margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; } An alternative to resetting/removing browser defaults is to normalize them—that is, ensure all browsers use the same default settings for all elements. Many popular sites make use of normalize.css, which can be found at https://github.com/necolas/ normalize.css. 4.4 Selectors 135 #first {.orange { background-color: seagreen; background-color: orange; } }.circle { background-color: royalblue; border-radius: 50%; } FIGURE 4.4 Id and class selector example 4.4.3 Id Selectors An id selector allows you to target a specific element by its id attribute regardless of its type or position. If an HTML element has been labeled with an id attribute, then you can target it for styling by using an id selector, which takes the form: pound/ hash (#) followed by the id name. Figure 4.4 illustrates the use of an id selector. NOTE Id selectors should only be used when referencing a single HTML element since an id attribute can only be assigned to a single HTML element. Class selectors should be used when (potentially) referencing several related elements. It is worth noting, however, that the browser is quite forgiving when it comes to id selectors. While you should only use a given id attribute once in the markup, the browser is willing to let you use it multiple times! 136 CHAPTER 4 CSS 1: Selectors and Basic Styling input[type="text"] { This attribute selector selects only height: 40px; those elements whose type border-style: none; attribute is exactly equal to "text". border-bottom: 2px solid blue; background-color: beige; } ****** a[href$=".pdf"] { This attribute selector selects background: url(pdf_icon.svg) no-repeat left center; only those elements whose padding-left:19px; href attribute value ends with } the characters ".pdf". First link One PDF First link One PDF Two PDF Two PDF FIGURE 4.5 Attribute selector example 4.4.4 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. This can be a very powerful technique, but because of uneven support by some of the browsers in the past, not all web authors have used them. Attribute selectors can be a very helpful technique in the styling of hyperlinks and form elements. In the next chapter, you will learn the HTML for constructing forms. Many of the different form widgets, such as text boxes, radio buttons, and password fields, are all constructed from the same element. You use the type attribute to indicate which form widget you want. You typically will want to style the different widgets in quite different ways; the attribute selector provides a common way to achieve this goal. Figure 4.5 illustrates two different uses of attri- bute selectors: the first to style form elements and the second to style links to PDF files differently than other links. Table 4.4 summarizes some of the most common ways one can construct attri- bute selectors in CSS. 4.4.5 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 but which is still a recognizable selectable 4.4 Selectors 137 Selector Matches Example [] A specific attribute. [title] Matches any element with a title attribute [=] A specific attribute with a a[title="posts from this country"] specific value. Matches any element whose title attribute is exactly “posts from this country“ [~=] A specific attribute whose [title~="Countries"] value matches at least one of Matches any title attribute that contains the words in a space-delimited the word “Countries“ list of words. [^=] A specific attribute whose a[href^="mailto"] value begins with a specified Matches any element whose href value. attribute begins with “mailto“ [*=] A specific attribute whose img[src*="flag"] value contains a substring. Matches any element whose src attribute contains somewhere within it the text “flag“ [$=] A specific attribute whose a[href$=".pdf"] value ends with a specified Matches any element whose href value. attribute ends with the text “.pdf“ TABLE 4.4 Attribute Selectors object. For instance, you can select the first line or first letter of any HTML element using a pseudo-element selector. A pseudo-class selector does apply to an HTML element but targets either a particular state or a variety of family relationships. Table 4.5 lists some of the more common pseudo-class and pseudo-element selectors. The most common use of this type of selectors is for targeting link states and for adding hover styling for other elements. By default, the browser displays link text blue and visited text links purple. Figure 4.6 illustrates the use of pseudo-class selectors to style hover behavior and the appearance of links. Do be aware that hover state does not occur on touch screen devices. Note the syntax of pseudo-class selectors: the colon (:) followed by the pseudo-class selector name. Do be aware that a space is not allowed after the colon. Believe it or not, the order of these pseudo-class elements is important. The :link and :visited pseudo-classes should appear before the others. Some developers use a mnemonic to help them remember the order. My favorite is “Lord Vader, Former Handle Anakin” for Link, Visited, Focus, Hover, Active. 138 CHAPTER 4 CSS 1: Selectors and Basic Styling Selector Type Description a:link pseudo-class Selects links that have not been visited. a:visited pseudo-class Selects links that have been visited. :focus pseudo-class Selects elements (such as text boxes or list boxes) that have the input focus. :hover pseudo-class Selects elements that the mouse pointer is currently above. :active pseudo-class Selects an element that is being activated by the user. A typical example is a link that is being clicked. :checked pseudo-class Selects a form element that is currently checked. A typical exam- ple might be a radio button or a check box. :first-child pseudo-class Selects an element that is the first child of its parent. A common use is to provide different styling to the first element in a list. :last-child pseudo-class Selects last child element within parent. :nth-child() pseudo-class Selects child elements based on algebraic expression. :first-letter pseudo-element Selects the first letter of an element. Useful for adding drop- caps to a paragraph. :first-line pseudo-element Selects the first line of an element. TABLE 4.5 Common Pseudo-Class and Pseudo-Element Selectors Home Mens Womens Kids House se Garden Contact li:hover {... } Home Mens Womens Kids House Garden Contact li:first-child {... } Home Mens Womens Kids House Garden Contact li:nth-child(2n) {... } Home Mens Womens Kids House Garden Contact li:nth-child(2n-1) {... } Arsenal a:link {... } Chelsea a:visited { color: royalblue } Liverpool a:hover { color: lavender; background-color: hotpink} Manchester United a:active { font-weight: bold } click West Ham United a:link:last-child { text-decoration: none } Pseudo selectors can be combined FIGURE 4.6 Styling a link using pseudo-class selectors 4.4 Selectors 139 NOTE At different points in this book, you will see the use of "#" as the url for ele- ments. This is a common practice used by developers when they are first testing a design. The designer might know that there is a link somewhere, but the precise URL might still be unknown. In such a case, using the "#" url is helpful: the browser will recognize them as links, but nothing will happen when they are clicked. Later, using the source code editor’s search functionality will make it easy to find links that need to be finalized. 4.4.6 Contextual Selectors A contextual selector (in CSS3 also called combinators) allows you to select ele- ments based on their ancestors, descendants, or siblings. That is, it selects elements based on their context or their relation to other elements in the document tree. While some of these contextual selectors are used relatively infrequently, almost all web authors find themselves using descendant selectors. A descendant selector matches all elements that are contained within another element. The character used to indicate descendant selection is the space character. Figure 4.7 illustrates the syntax and usage of the syntax of the descendant selector. Table 4.6 describes the other contextual selectors. Figure 4.8 illustrates some sample uses of a variety of different contextual selectors. An interesting question about the selectors in Figure 4.8 is, “What will be the color of the first element?” Will it be red or purple (since it is targeted by two different selectors)? It will, in fact, be purple. The reason why (because it has a higher specificity) will be covered in the next section. NOTE You can combine contextual selectors with grouped selectors. The comma is like the logical OR operator. Thus, the grouped selector: div#main div time, footer ul li { color: red; } is equivalent to: div#main div time { color: red; } footer ul li { color: red; } context selected element div p { … } #main div p:first-child { … } Selects a element Selects the first element somewhere somewhere within a element within a element that is somewhere within an element with an id="main" FIGURE 4.7 Syntax of a descendant selection 140 CHAPTER 4 CSS 1: Selectors and Basic Styling Selector Matches Example Descendant A specified element that is div p contained somewhere within Selects a element that is contained somewhere another specified element. within a element. That is, the can be any descendant, not just a child. Child A specified element that is a div>h2 direct child of the specified Selects an element that is a child of a element. element. Adjacent A specified element that is the h3+p sibling next sibling (i.e., comes directly Selects the first after any. after) of the specified element. General All following elements that h3~p sibling shares the same parent as the Selects all the elements after an and that share specified element. the same parent as the. TABLE 4.6 Contextual Selectors ul a:link { Canada color: blue; Germany } United States descendant selector descendant selector div time { color: red; } #main>time { color: purple; 2019-12-25 } child selector By Ricardo on 2020-05-23 Easy on the HDR buddy. hr+p { color: green; By Susan on 2020-11-18 } I love Central Park. adjacent sibling selector Usage stats are here Social h3~p { Visits: 2300 color: orange; Shares: 5 } general sibling selector Home | Browse | FIGURE 4.8 Contextual selectors in action 4.4 Selectors 141 TOOL INSIGHT Browser Tools for CSS Modern browsers provide excellent tools that can help understand and debug CSS. Within Chrome and FireFox, you can select the Inspect option from the context menu. You can display this inspector as a separate window or attached to the browser. As can be seen in Figure 4.9, you can examine author-defined styles as well as browser defaults. You can examine calculated style settings, the box settings, grid set- tings, and more. This facility is also a great way of understanding how other authors have constructed their pages. Chrome DevTools Author- created style Browser style Inherited style This style has been overwritten by another Box Model Firefox Inspector FIGURE 4.9 Browser DevTools 142 CHAPTER 4 CSS 1: Selectors and Basic Styling TEST YOUR KNOWLEDGE #1 You have been provided markup in lab04-test01.html and styles within comments in to styles/lab04-test01.css. 1. Uncomment the styles and add CSS selectors so that it looks similar to that shown in Figure 4.10. You cannot modify the markup, so this will require work- ing with selectors. FIGURE 4.10 Completed Test Your Knowledge #1 4.5 The Cascade: How Styles Interact HANDS-ON EXERCISES In an earlier Pro Tip in this chapter, it was mentioned that in fact there are three different types of style sheets: author-created, user-defined, and the default LAB 4 CSS Cascade browser style sheet. As well, it is possible within an author-created stylesheet to define multiple rules for the same HTML element. For these reasons, CSS has a system to help the browser determine how to display elements when different style rules conflict. The “Cascade” in CSS refers to how conflicting rules are handled. The visual metaphor behind the term cascade is that of a mountain stream progressing down- stream over rocks (and not that of a popular dishwashing detergent). The down- ward movement of water down a cascade is meant to be analogous to how a given style rule will continue to take precedence with child elements (i.e., elements “below” in a document outline as shown in Figure 4.3). 4.5 The Cascade: How Styles Interact 143 CSS uses the following cascade principles to help it deal with conflicts: inheri- tance, specificity, and location. 4.5.1 Inheritance Inheritance is the first of these cascading principles. Many (but not all) CSS proper- ties affect not only themselves but their descendants as well. Font, color, list, and text properties (from Table 4.1) are inheritable; layout, sizing, border, background, and spacing properties are not. Figures 4.11 and 4.12 illustrate CSS inheritance. In the first example, only some of the property rules are inherited from the element. That is, only the body element (thankfully!) will have a thick green border and the 100-px margin; however, all the text in the other elements in the document will be in the Arial font and colored red. In the second example in Figure 4.12, you can assume there is no longer the body styling, but instead we have a single style rule that styles all the ele- ments. The and elements within the inherit the bold font-weight property but not the margin or border styles. However, it is possible to tell elements to inherit properties that are normally not inheritable, as shown in Figure 4.13. In comparison to Figure 4.12, notice how body { font-family: Arial; Inherited color: red; Inherited border: 8pt solid green; Not inherited margin: 60px; Not inherited } FIGURE 4.11 Inheritance 144 CHAPTER 4 CSS 1: Selectors and Basic Styling div { font-weight: bold; Inherited margin: 50px; Not inherited border: 1pt solid green; Not inherited } FIGURE 4.12 More inheritance div { font-weight: bold; margin: 50px; border: 1pt solid green; } p { border: inherit; margin: inherit; } Reviews By Ricardo on 2016-05-23 Easy on the HDR buddy. By Susan on 2016-11-18 I love Central Park. FIGURE 4.13 Using the inherit value 4.5 The Cascade: How Styles Interact 145 the elements nested within the elements now inherit the border and mar- gins of their parent. 4.5.2 Specificity Specificity is how the browser determines which style rule takes precedence when more than one style rule could be applied to the same element. In CSS, the more specific the selector, the more it takes precedence (i.e., overrides the previous definition). Another way to define specificity is by telling you how it works. The way that specificity works in the browser is that the browser assigns a weight to each style rule; when several rules apply, the one with the greatest weight takes precedence. NOTE Most CSS designers tend to avoid using the inherit property since it can usually be replaced with clear and obvious rules. For instance, in Figure 4.13, the use of inherit can be replaced with the more verbose, but clearer, set of rules: div { font-weight: bold; } p, div { margin: 50px; border: 1pt solid green; } In the example shown in Figure 4.14, the color and font-weight properties defined in the element are inheritable and thus potentially applicable to all the child elements contained within it. However, because the and ele- ments also have the same properties set, they override the value defined for the element because their selectors ( and ) are more specific. As a con- sequence, their font-weight is normal, and their text is colored either green or magenta. As you can see in Figure 4.14, class selectors take precedence over element selec- tors, and id selectors take precedence over class selectors. The precise algorithm the browser is supposed to use to determine specificity is quite complex.6 A simplified version is shown in Figure 4.15. 146 CHAPTER 4 CSS 1: Selectors and Basic Styling body { font-weight: bold; This text is not within a p element. color: red; Reviews } div { By Ricardo on 2016-05-23 font-weight: normal; Easy on the HDR buddy. color: magenta; This text is not within a p element. } p { By Susan on 2016-11-18 color: green; I love Central Park. }.last { By Dave on 2016-11-24 color: blue; Thanks for posting. } #verylast { color: orange; font-size: 16pt; } FIGURE 4.14 Specificity 4.5.3 Location Finally, when inheritance and specificity cannot determine style precedence, the prin- ciple of location will be used. The principle of location is that 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. Similarly, an embedded style will override an equally specific rule defined in an external author style sheet if it appears after the external sheet’s element. Styles defined in external author style sheet X will override styles in external author style sheet Y if X’s element is after Y’s in the HTML document. Similarly, 4.5 The Cascade: How Styles Interact 147 Specificity Value inline style attribute 1000 A higher specificity value overrides 1 overrides lower specificity values. id + div #firstExample { additional color: grey; 0101 selectors } 2 overrides #firstExample { id selector color: magenta; 0100 } 3 overrides.example { color: blue; class and attribute } 0010 selectors a[href$=".pdf"] { color: blue; } 4 overrides descendant selector div form { (elements only) color: orange; 0002 } 5 overrides div { element selector color: green; 0001 } FIGURE 4.15 Specificity algorithm when the same style property is defined multiple times within a single declaration block, the last one will take precedence. Figure 4.16 illustrates how location affects precedence. Can you guess what will be the color of the sample text in Figure 4.16? The color of the sample text in Figure 4.16 will be red. What would be the color of the sample text if there wasn’t an inline style definition? It would be magenta. 148 CHAPTER 4 CSS 1: Selectors and Basic Styling Browser’s default style settings user-styles.css #example { 1 overrides color: green; } overrides 2 3 overrides overrides 4 #example { #example { color: orange; 5 overrides color: blue; color: magenta; } } 6 overrides sample text FIGURE 4.16 Location PRO TIP The algorithm that is used to determine specificity of any given element is defined by the W3C as follows: First count 1 if the declaration is from a “style” attribute in the HTML, 0 otherwise (let that value = a). Count the number of ID attributes in the selector (let that value = b). Count the number of class selectors, attribute selectors, and pseudo-classes in the selector (let that value = c). Count the number of element names and pseudo-elements in the selector (let that value = d). Finally, concatenate the four numbers a+b+c+d together to calculate the selector’s specificity. 4.6 The Box Model 149 The following sample selectors are given along with their specificity value: 1000 body.example 0011 body.example strong 0012 div#first 0101 div#first.error 0111 #footer.twitter a 0111 #footer.twitter a:hover 0121 body aside#left div#cart strong.price 0214 It should be noted that in general you don’t really need to know the specificity algorithm in order to work with CSS. However, knowing it can be invaluable when one is trying to debug a CSS problem. During such a time, you might find yourself asking the question, “Why isn’t my CSS rule doing anything? Why is the browser ignoring it?” Quite often the answer to that question is that a rule with a higher specificity is taking precedence. PRO TIP There is one exception to the principle of location. If a property is marked with !important (which does not mean NOT important, but instead means VERY important) in an author-created style rule, then it will override any other author-created style regardless of its location. The only exception is a style marked with !important in a user style sheet; such a rule will override all others. Of course, very few users know how to do this, so it is a pretty uncommon scenario. 4.6 The Box Model HANDS-ON In CSS, all HTML elements exist within an element box shown in Figure 4.17 (also EXERCISES known as the box model). In order to become proficient with CSS, you must become LAB 4 familiar with the box model. Block vs Inline Backgrounds and Shadow 4.6.1 Block versus Inline Elements Borders, Margins, Within CSS there are two types of element boxes: block level and inline boxes. and Padding Block-level elements such as , , , , and are each contained Box Sizing on their own line. Because block-level elements begin with a line break (that is, they Overflow start on a new line), without styling, two block-level elements can’t exist on the same line, as shown in Figure 4.18. Block-level elements use the normal CSS box model, in that they have margins, paddings, background colors, and borders. 150 CHAPTER 4 CSS 1: Selectors and Basic Styling margin border padding Every CSS rule begins with a selector. The selector identifies width which element or elements in the HTML document will be height affected by the declarations in the rule. Another way of thinking of selectors is that they are a pattern which is used element content area by the browser to select the HT ML elements that will receive background-color/background-image of element background-color/background-image of element’s parent 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. Another way of thinking of selectors is that they are a pattern that is used by the browser to select the HTML elements that will receive FIGURE 4.17 CSS box model Each block exists on its own line and is displayed in normal flow from the browser window’s top to its... bottom. By default each block-level element fills up the entire width of its parent (in this case, it is the... , which is equivalent to the width of the browser window).... You can use CSS box model properties to customize, for instance, the width of the box, and the margin space between other block-level elements. FIGURE 4.18 Block-level elements 4.6 The Box Model 151 This photo of Conservatory Pond in Central Park was taken with a Canon EOS 30D camera. Inline content is laid out horizontally left to right within its container. Once a line is filled with text text content, the next line will receive the remaining content, and so on. text text Here the content of this element is displayed on two lines. If the browser window resizes, then inline content will be “reflowed” based on the new width. text text Here the content of this element is now displayed on three lines. text text FIGURE 4.19 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. Inline elements line up next to one another horizontally from left to right on the same line; when there isn’t enough space left on the line, the content moves to a new line, as shown in Figure 4.19. In a document with normal flow, block-level elements and inline elements work together as shown in Figure 4.20. Block-level elements will flow from top to bot- tom, while inline elements flow from left to right within a block. If a block contains other blocks, the same behavior happens: the child blocks flow from the top to the bottom of the parent block. It is possible to change whether an element is block-level or inline via the CSS display property. Consider the following three CSS rules: span { display: block; } li { display: inline; } img { display: inline-block; } 152 CHAPTER 4 CSS 1: Selectors and Basic Styling A document consists of block-level elements stacked text text from top to bottom. text text Within a block, inline content is horizontally placed left to right. text text Some block-level elements can contain other block-level text elements (in this example, a can contain other blocks). In such a case, the block-level text content inside the parent is stacked from top to bottom within the container (). text … … FIGURE 4.20 Block and inline elements together ESSENTIAL SOLUTIONS Horizontal List ul#menu li { Home display: inline-block; result in browser Mens list-style-type: none; Womens } Kids Home Mens Womens Kids 4.6 The Box Model 153 These rules will make all elements behave like block-level elements, all elements like inline (that is, each list item will be displayed on the same line), and all elements that will flow like inline elements but which have a block element box. 4.6.2 Background As can be seen in Figure 4.17, the background of an element fills an element out to its border (if it has one, that is). In contemporary web design, it has become extremely common to use CSS to display purely presentational images (such as background gradients and patterns, decorative images, etc.) rather than using the element. Table 4.7 lists the most common background properties. While background colors are relatively straightforward, background images are a bit more complicated. Figure 4.21 illustrates how some of the different back- ground image properties interact. Property Description background A combined shorthand property that allows you to set multiple background values in one property. While you can omit properties with the shorthand, do remember that any omitted properties will be set to their default value. background-attachment Specifies whether the background image scrolls with the document (default) or remains fixed. Possible values are: fixed, scroll, local. background-color Sets the background color of the element. You can use any of the techniques shown in Table 4.2 for specifying the color. background-image Specifies the background image (which is generally a jpeg, gif, or png file) for the element. Note that the URL is relative to the CSS file and not the HTML. Gradient color fills (covered in Chapter 7) can also be specified with this property. background-origin Sets the beginning location of the image within its parent. background-position Specifies where on the element the background image will be placed. Some possible values include: bottom, center, left, and right. You can also supply a pixel or percentage numeric position value as well. When supplying a numeric value, you must supply a horizontal/vertical pair; this value indicates its distance from the top left corner of the element, as shown in Figure 4.21. background-repeat Determines whether the background image will be repeated. This is a common technique for creating a tiled background (it is in fact the default behavior), as shown in Figure 4.21. Possible values are: repeat, repeat-x, repeat-y, and no-repeat. background-size Sets the size of the image and how the image should fill the space within the parent. TABLE 4.7 Common Background Properties 154 CHAPTER 4 CSS 1: Selectors and Basic Styling ESSENTIAL SOLUTIONS Text on top of an image #container { Title background-image: url(bigimage.jpg); more stuff background-repeat: no-repeat; background-size: cover; width: 100%; min-height: 300px; padding: 200px; Title } more stuff result in browser 50px 300px background-image: url(checkers.png); background-image: url(checkers.png) no-repeat; background-repeat: no-repeat; background-position: 300px 50px; background-repeat:repeat; background-repeat:repeat-y; background-repeat:repeat-x; background-size:cover; background-size:contain; background-size:200px 100px; background-origin:border-box; background-origin:padding-box; background-origin:content-box; background-size:cover; padding: 10px; border-size: 5px; border-color: rgba(242,112,90,0.5) FIGURE 4.21 Background image properties 4.6 The Box Model 155 4.6.3 Borders and Box Shadow Borders and shadows provide a way to visually separate elements. You can put bor- ders around all four sides of an element, or just one, two, or three of the sides. Table 4.8 lists the various border and shadow properties and Figure 4.22 illustrates several of these properties in action. Border widths are perhaps the one exception to the general advice against using the pixel measure. Using em units or percentages for border widths can result in unpredictable widths as the different browsers use different algorithms (some round up, some round down) as the zoom level increases or decreases. For this reason, border widths are almost always set to pixel units. border-style: solid; border-style: dotted; border-style: dashed; border-width: 0; border-width: 1px; border-width: 1px 2px 0 1px; border: solid 2px gold; border-radius: 3px; border-radius: 3px; border-width: 1px; border-width: 0; box-shadow: 2px 2px gray; box-shadow: 2px 2px 2px 2px gray; FIGURE 4.22 Border and shadow properties 156 CHAPTER 4 CSS 1: Selectors and Basic Styling Property Description border A combined shorthand property that allows you to set the style, width, and color of a border in one property. The order is important and must be: border-width border-style border-color border-style Specifies the line type of the border. Possible values are: solid, dotted, dashed, double, groove, ridge, inset, outset, hidden, and none. border-width The width of the border in a unit (but not percents). A variety of keywords (thin, medium, etc.) are also supported. border-color The color of the border in a color unit. border-radius The radius of a rounded corner. border-image The URL of an image to use as a border. box-shadow Adds a shadow effect to an element. The values are as follows: offset-x offset-y blur-radius spread-radius color TABLE 4.8 Border Properties The box-shadow property provides a way to add shadow effects around an element’s box. To set the shadow, you specify x and y offsets, along with optional blur, spread, inset, and color settings. 4.6.4 Margins and Padding Margins and padding are essential properties for adding white space to a web page, which can help differentiate one element from another. Figure 4.23 illustrates how these two properties can be used to provide spacing and element differentiation. As you can see in Figures 4.17 and 4.23, margins add spacing around an ele- ment’s content, while padding adds spacing within elements. Borders divide the margin area from the padding area. ESSENTIAL SOLUTIONS Centering an element horizontally within a container content In chapter 7, you will learn how to use flexbox layout to position an result in browser element horizontally and vertically #element { within a container. margin: 0 auto; width: 200px; Element } 4.6 The Box Model 157 Every CSS rule begins with a selector. The selector identifies which element or elements in the HTML p { document will be affected by the declarations in the rule. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive border: solid 1pt red; Every CSS rule begins with a selector. The selector identifies which element or elements in the HTML margin: 0; document will be affected by the declarations in the rule. Another way of thinking of selectors is that padding: 0; they are a pattern which is used by the browser to select the HTML elements that will receive 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. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive Every CSS rule begins with a selector. The selector identifies which element or elements in the HTML p { document will be affected by the declarations in the rule. Another way of thinking of selectors is that border: solid 1pt red; they are a pattern which is used by the browser to select the HTML elements that will receive margin: 30px; 30px padding: 0; 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. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive 30px 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. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive 30px p { Every CSS rule begins with a selector. The selector identifies which element or elements in the border: solid 1pt red; HTML document will be affected by the declarations in the rule. Another way of thinking of margin: 0; selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive padding: 30px; 30px } 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. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive 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. Another way of thinking of selectors is that they are a pattern which is used by the browser to select the HTML elements that will receive FIGURE 4.23 Borders, margins, and padding provide element spacing and differentiation There is a very important thing to notice about the margins in Figure 4.23. Did you notice that the space between paragraphs one and two and between two and three is the same as the space before paragraph one and after paragraph three? This is due to the fact that adjoining vertical margins collapse. 158 CHAPTER 4 CSS 1: Selectors and Basic Styling 1 90px 50px Every CSS rule... Every CSS rule begins with a selector. The selector identifies which element or elements Every CSS rule... in the HTML document will be affected by the declarations in the rule. Another way of 50px 4 Every CSS rule begins with a selector. The selector identifies which element or elements Every CSS rule... in the HTML document will be affected by the declarations in the rule. Another way of Every CSS rule... 50px 2 90px div { border: dotted 1pt green; 50px padding: 0; Every CSS rule begins with a selector. The selector identifies which element or elements margin: 90px 20px; in the HTML document will be affected by the declarations in the rule. Another way of } 50px 5 Every CSS rule begins with a selector. The selector identifies which element or elements p { in the HTML document will be affected by the declarations in the rule. Another way of border: solid 1pt red; 50px padding: 0; margin: 50px 20px; 3 90px } FIGURE 4.24 Collapsing vertical margins 1 11 1 11 2 12 1 11 Figure 4.24 illustrates how adjoining 2 vertical 12 3 margins collapse 13 in the browser. If overlapping margins did not collapse, then margin space for 2 would 12 be 180 px 3 13 4 14 (90 px for the bottom margin of the first + 90 px for the3 top13 margin of the second ), while the margins for 4 and 5 would 14 15 be 100 px. However, as you 4 14 can see in Figure 4.24, this is not the case. 5 15 6 16 The W3C specification defines this behavior as collapsing margins: 5 15 6 16 7 17 6 16 In CSS, the adjoining margins of two 7 or17 more 8 boxes 18 (which might or might not be 7 siblings) can combine to form a single margin. Margins that combine 17 this way are 8 18 9 19 said to collapse, and the resulting combined margin is called a 8collapsed 18 margin. 9 19 10 20 9 19 What this means is that when the10vertical 20 margins of two elements touch, only the largest margin value of the elements will be displayed, while 20 smaller mar- 10 the gin value will be collapsed to zero. Horizontal margins, on the other hand, never collapse. To complicate matters even further, there is a large number of special cases in which adjoining vertical margins do not collapse (see the W3C Specification for more detail). From our experience, collapsing (or not collapsing) margins are one of the main problems (or frustrations) that our students face when working with CSS. 4.6 The Box Model 159 NOTE With border, margin, and padding properties, it is possible to set the properties for one or more sides of the element box in a single property, or to set them individually using separate properties. For instance, we can set the side properties 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; When using this multiple values shortcut, they are applied in clockwise order, starting at the top. Thus the order is top right bottom left, as shown in Figure 4.25. The mnemonic TRouBLe might help you memorize this order. TRBL (Trouble) border-color: top right bottom left; Top border-color: red green orange blue; Left Right border-color: red green; Bottom FIGURE 4.25 CSS TRBL (Trouble) shortcut 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; 4.6.5 Box Dimensions As you have already learned, block-level elements have width and height properties. They also have a min-width, min-height, max-width, and max-height properties as well. These min and max versions allow the designer to specify a size that an ele- ment cannot go under or over. Why are these necessary? One reason is that a width or a height might be specified as a % of its parent container. For very large or very small displays, this % value might make the element 160 CHAPTER 4 CSS 1: Selectors and Basic Styling too large or too small. One solution is to specify an additional min or max width/ height value for the element. All in all, box dimensions frequently confound new CSS authors. Why is this the case? One reason is that only block-level elements and nontext inline elements such as images have a width and height that you can specify. By default (in CSS this is the auto value), the width and height of elements is the actual size of the content. For text, this is determined by the font size and font face; for images, the width and height of the actual image in pixels. 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. This is something that tends to give beginning CSS students trouble. Figure 4.26 illustrates the default content-box element sizing behavior. It also shows the newer alternative border-box approach, which is more intuitive. Indeed, many developers now add a set of rules to the beginning of their CSS that makes border-box the box-sizing model for all elements. For block-level elements such as and elements, there are limits to what the width and height properties can actually do. You can shrink the width, but the content still needs to be displayed, so the browser may very well ignore the height that you set. As you can see in Figure 4.27, the default width is the browser viewport. But in the second screen capture in the image, with the changed width and height, there is not enough space for the browser to display all the content within the element. So while the browser will display a background color of 200 × 100 px (i.e., the size of the element as set by the width and height properties), the height of the actual textual content is much larger (depending on the font size). 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, as shown in Figure 4.28. While the example CSS in Figure 4.27 uses pixels for its measurement, some contemporary designers prefer to use percentages or em units for widths and heights. ESSENTIAL SOLUTIONS Using border-box in entire document html { box-sizing: border-box; } *, *:before, *:after { Normally, box-sizing isn’t a property that is box-sizing: inherit; inherited. This makes it inheritable by every } element within 4.6 The Box Model 161 left margin 10 10 top margin div { left border 2 2 top border box-sizing: content-box; width: 200px; left padding 5 5 top padding height: 100px;