Website: CSS.doc - ZhaochengLi/Zhaocheng-s GitHub Wiki
- Cascading Style Sheets
- Formatting Text (Plus More Selectors)
- Colors and Backgrounds (Plus Even More Selectors and External Style Sheets)
- Thinking Inside the Box (Padding, Borders, and Margins)
- Floating and Positioning
- Page Layout with CSS
- Transitions, Transforms, and Animation
- CSS Techniques
Cascading Style Sheets (CSS) is the W3C standard for defining the presentation of documents written in HTML, and in fact, any XML language. Presentation, again, refers to the way the document is displayed or delivered to the user, whether on a computer screen, a cell phone display, printed on paper, or read aloud by a screen reader.
- How it works?
- Start with a document that has been marked up in HTML.
- Write style rules for how you'd like certain elements to look.
- Attach the style rules to the document. When the browser displays the document, it follows your rules for rendering elements (unless the user has applied some mandatory styles, but we'll get to that later).
- Writing the rules
-
A style sheet is made up of one or more style instructions (called rules or rule sets) that describe how an element or group of elements should be displayed. Each rule selects an element and declares how it should look.
-
In CSS terminology, the two main sections of a rule are the selector that identifies the element or elements to be affected, and the declaration that provides the rendering instructions.
-
The declaration, in turn, is made up of a property (such as
color
) and its value (green), separated by a colon and a space.selector {property: values;} // or selector { property1: value1; property2: value2; proeprty3: value3; }
- Attaching the styles to the document. We embedded the style sheet right in the document using the
style
element. That is just one of the three ways that style information can be applied to an HTML document.
-
External style sheets. An external style sheet is a separate, text-only document that contains a number of style rules. It must be named with the .css suffix.
-
Embedded style sheets. This is placed in a document using the style element, and its rules apply only to that document. The style element must be placed in the head of the document.
<head> <title>Required document title here</title> <style> /* style rules go here */ </style> </head>
-
Inline styles. You can apply properties and values to a single element using style attribute in the element itself:
<h1 style="color: red; margin-top: 2em">Introduction</h1>
-
Interitance. You can use inheritance to your advantage when writing style sheets. For example, if you want all text elements to be rendered in the Verdana font face, you could write separate style rules for every element in the document and set the font-face to Verdana. A better way would be to write a single style rule that applies the font-face property to the body element, and let all the text elements contained in the body inherit that style. Any property applied to a specific element will override the inherited values for that property.
-
Conflicting Styles: the Cascade. CSS allows you to apply several style sheets to the same document, which means there are bound to be conflict. The folks who wrote the style sheet specification anticipated this problem and advised a hierarchical stytem that assigns different weights to the various sources of style information. The cascade refers to what happens when several sources of style information vie for control of the elements on a page: style information is passed down ("cascades" down) until it is overridden by a style command with more weight.
-
To prevent a specific rule from being overridden, you can assign "importance" with the !important indicator.
p{color: blue !important;}
Style Sheet Hierarchy (from general to specific, items lower in the list will overrid items above them;)
- Browser default settings
- User style settings (set in a browser as a "reader style sheet")
- Linked external style sheet (added with the link element)
- Imported style sheets (added with the
@import
function) - Embedded style sheets (added with the style element)
- Inline style information (added with the style attribute in an opening tag)
- Any style rule marked
!important
by the author - Any stile rule marked
!important
by the reader (user)
Rule Order: if there are conflicts within style rules of identical weight, whichever one comes last in the list "wins". For example,
<style>
p {color: red;}
p {color: blue;}
</style>
/* in this scenario, the paragraph will be blue. */
-
The box model, it is the cornerstone of the CSS visual formatting system. The easiest way to think of the box model is that browsers see every element on the page (both block and inline) as being contained in a little rectangular box. You can apply properties such as borders, margins, padding and backgrounds to these boxes, and even reposition them on the page.
-
Grouped selectors, if you ever need to apply the same property to a number of elements, you can group the selectors into one rule by separating them with commas.
h1, h2, p, em, img {border: 1px solid blue;}
- The Font Properties
- Changing Text Color
- A Few More Selector Types
- Text Line Adjustments
- Underlines and Other "Decorations"
- Changing Capitalization
- Spaced Out
- Text Shadow
- Changing List Bullets and Numbers
At a glance, the font-related properties:
It is used to specify a font or list of fonts (known as a font stack).
-
Value: one or more font or generic font family names, separated by commas / inherit
-
Default: depends on the browser
-
Applies to: all elements
-
Inherits: yes
-
Examples:
body {font-family: Arial;} p {font-family: "Duru Sans", Courier, monospace;} // notice for font names with character space, we must use quotation marks.
-
Why do we need to list more than one font? It is because browsers are limited to displaying fonts they have access to. So CSS allows us to provide a list of back-up fonts, or font stack. If the first specified font is not found, the browser tries the next one, and down through the list until it finds one that works.
-
Generic font families. There are five of them, when you specify a generic font family, the browser chooses an available font from that stylistic vategory. Generic font family names do not need to be capitalized.
- serif, ex., Times, Times New Roman
- sans-serif, ex., Arial, Arial Black, Verdana
- monospace, ex., Courier, Courier New
- cursive, ex., Apple Chancery, Comic Sans
- fantasy, ex., Impact, Western
-
Best Font Stack Combinations, we here only mention one:
Monospace: "Andale Mono WT", "Andale Mono", "Lucida Console", "Liberation Mono", "Courier New", Courier, Monospace;
It is used to specify the size of the text.
-
Value: length unit / pertentage / xx-small / x-small / small / medium / large / x-large / xx-large / smaller / larger / inherit
-
Default: medium
-
Applies to: all elements
-
Inherits: yes
-
Examples:
h1 {font-size: 1.5em;} h2 {font-size: 150%}
-
Percentage values: usually, the body element has been specified as 100% of the default text size (generally 16 pixels).
CSS Units of Measurement, ther are two categories:
-
Realtive units: they are based on the size of something else, such as the default text size or the size of the parent element.
-
px
, pixel, considered relative in CSS2.1 because it varies with display resolution. -
em
, a unit of measurement equal to the current font size. -
ex
, x-height, approximately the height of a lowercase "x" in the font.
-
-
Absolute units: it should be avoided for web page style sheets because they are not relavant on computer screens. However, if you are creating a style sheet to be used when the document is printed, they may be just the ticket.
-
px
, pixel, predefined as an asolute measurement equal to 1/96 of an inch in CSS3. -
pt
, points (1/72 inch) -
pc
, picas, 1 picas = 12 points = 1/6 inch -
mm
, millimeters -
cm
, centimeters -
in
, inches
-
em
measurements: it is calculated as the distance between baselines when the font is set without any extra space between the lines. For text width with a font size of 16 pixels, an em
measures 16 pixels; for 12-pixel text, an em
euqals 12 pixels, and so on.
Percentages, it is more straightforward with percentages, which measures relatively to the parent length. When the parent width is 800px
then 50%
would become 400px
.
Keywords, they are predefined absolute keywords: xx-large, x-large, large, medium, small, x-small, xx-small. The keywords do not correspond to particular measurements, but rather are scaled consistently in relation to one another. medium is set as default in current browser. The relative keywords, larger and smaller, are used to shift the size of text relative to the size of the parent element text. The exact amount of the size change is determined by each browser and is out of control.
-
Value: normal / bold / bolder / lighter / 100 / 200 / 300 / ... / 900 / inherit
-
Default: normal
-
Applies to: all elements
-
Inherits: yes
-
Examples:
dt {font-weight: bold;}
-
Value: normal / italic / oblique / inherit
-
Default: normal
-
Applies to: all elements
-
Inherits: yes
-
Examples:
strong {font-style: italic;}
This is a separate font design that uses small uppercase-type letters in place of lowercase letter designs.
- Value: normal / small-caps / inherit
- Default: normal
- Applies to: all elements
- Inherits: yes
This is a shortcut.
-
Value: font-style font-weight font-variant font-size/line-height font-family / inherit
-
Default: depends on default value for each proprty listed
-
Applies to: all elements
-
Inherits: yes
-
Examples:
h3 { font: oblique bold small-caps 1.5em/1.8em Verdana sans-serif; }
-
Value: color value (name or numeric)
-
Default: depends on the browser and user's preferences
-
Applies to: all elements
-
Inherits: yes
-
Examples:
h1 {color gray;} h1 {color #666666;}
-
Element selectors
p {color: navy;}
-
Grouped selectors
p, ul, td {color: navy;}
-
Descendant selectors. A descendant selector targets elements that are contained within (and therefore are descendant of) another element.
li em {color: olive;} ol a em {font-variant: small-caps;}
-
ID selectors. We learned about the id attribute that gives an element a unique identifying name. The id attribute can be used with any HTML element, and it is commonly used to give meaning to the generic div and span elements. ID selectors allow you to target elements by their id values.
<li id="catalog1234">Happy Face T-thirt</li> li#catalog1234 {color: red;} // or #catalog1234 {color: red;} // or you can also use ID selector as part of a contextual selector #links li {margin-left: 10px;}
-
Class selectors. As we learned before, the class identifier is used to classify elements into a conceptual group. Unlike the id attribute, multiple elements may share a class name. Not only that but an element may belong to more than one class. You can target elements belonging to the same class with a class selector. Class names are indicated with a period (.) at the beginning of the selector.
//suppose we have a class="special" p.special {color: orange;} // or simply .special {color: orange;}
-
Universal selector, we use an universal element selector (*) to match any element
// all element * {color:gray;} // all in id="intro" #intro * {color: gray;}
Specificity, the actual system CSS uses for calculating selector specificity is quite complicated, but this list of selector types from most to least specific should serve you well in most scenarios.
- ID selectors
- Class selectors
- Contextual selectors
- Individual element selectors
line-height
: to specify a "minimum" distance because it you put a tall image or large characters on a line, the height of that line will expand to accommodate it.
-
Value: number / leangth measurement / percentage / normal / inherit
-
Default: normal
-
Applies to: all elements
-
Inherits: yes
-
Examples:
p {line-height: 2;} // it acts as a scaling factor that is multiplied by the current font size to calculate the line-height value. p {line-height: 2em;} p {line-height: 150%;}
-
Value: length measurement / percentage / inherit
-
Default: 0
-
Applies to: block-level elements, table cells, and inline blocks
-
Inherits: yes
-
Examples:
p#1 {text-indent: 2em;} p#2 {text-indent: 25%;} p#3 {text-indent: -35px} // other direction
- Value: left / right / center / justify / inherit
- Default: left for languages that read left to right; right for languages that read right to left
- Applies to: block-level elements, table cells, and inline blocks
- Inherits: yes
- Examples:
- text-align: left: aligns text on the left margin;
- text-align: right: aligns text on the right margin;
- text-align: center: centers text in the text block;
- text-align: justify: aligns text on both left and right margins;
Value: none / underline / overline / line-through / blink Default: none Applies to: all elements Inherits: no, but since lines are drawn across child elements, they may look like they are "decorated" too. Examples:
a {text-decoration: blink;} // makes text flash on and off
- Value: none / capitalize / lowercase / uppercase / inherit
- Default: none
- Applies to: all element
- Inherits: yes
- Examples:
- text-transform: capitalize // capitalizes the fitst letter of each word
-
Values: length measurement / normal / inherit
-
Default: normal
-
Applies to: all elements
-
Inherits: yes
-
Examples:
p {letter-spacing: 8px;}
-
Values: length measurement / normal / inherit
-
Default: normal
-
Applies to: all elements
-
Inherits: yes
-
Examples:
p {word-spacing: 1.5em;}
text-shadow
: text shadows are drawn behind the text but in front of the background and border if there is one.
-
Values: 'horizontal offset' 'vertical offset' 'blur radius' 'color' / none
-
Default: none
-
Applies to: all elements
-
Inherits: yes
-
Examples:
h1 { color: darkgreen; text-shadow: .2em .2em .05em silver; }
There are some predefined beautiful templates online, you can browse if you need.
- Values: none / disc / circle / square / decimal / decimal-leading-zero / lower-alpha / upper-alpha / lower-latin / upper-latin / lower-roman / upper-roman / lower-greek / inherit
- Default: disc
- Applies to: ul, ol, and li (or elements whose display value is list-item)
- Inherits: yes
- Values: inside / outside / inherit
- Default: outside
- Applies to: ul, ol, and li (or ... list-item)
- Inherits: yes
-
Values: url / none / inherit
-
Default: none
-
Applies to: ... ... same as above
-
Inherits: yes
-
Examples:
// we can use list-style-type as backup in case the image does not display or the property is not supported by the browser or other user agent ul { list-style-image: url(/images/happy.gif); list-style-type: circle; list-style-position: outside; }
- Specifying Color Values
- Foreground Colors
- Backgorund Colors
- Playing with Opacity
- Introducing ... Pseudo-class Selectors
- Pseudo-element Selectors
- Attribute Selectors
- Background Images
- The Shorthand Backgorund Property
- Like A Rainbow (Gradients)
- External Style Sheets
There are two main way to specify colors in style sheets:
- with a predefined color name:
color: red;
- with a numeric value that describes a particular RGB color (the color model on computer monitors):
color: #FF0000;
color names
color: silver;
background-color: gray;
RGB color values
-
another common way to specify a color is by its RGB value.
-
computers create the colors you see on a moniter by combining three colors of light: red, green, and blue. This is known as the RGB color model. You can provide recipes (of sorts) for colors by telling the computer how much of each color to mix in.
-
CSS allows RGB color values to be specified in a number of formats. We could add it to a style sheet by listing each value on a scale from 0 to 255.
color: rgb(200, 178, 230); // less common color: rgb(78%, 70%, 90%); // six-digit hexadecimal version that we saw in the color pickers. These six digits represent the same three RGB values, except they have been converted into hexadecimal (or hex for short) equivalents. color: #C8B2E6; // notice #FFCC00 = #FC0
RGBa color
-
it allows you to specify a color and also make it as transparent or as opaque as you like. The "a" is an additional channel that controls the level of transparency on a scale from 0(fully transparent) to 1(fully opaque).
color: rgba(0,0,0,.5)
The foreground of an element consists of its text and border (if one is specified).
color:
-
Values: color value (name or numeric) | inherit
-
Default: depends on the browser and user's preferences
-
Applies to: all elements
-
Inherits: yes
-
Examples:
blockquote{ border: 4px dashed; color: #508C19; }
background-color
-
Values: color value (name or numeric) | transparent | inherit
-
Default: transparent
-
Applies to: all elements
-
Inherits: no
-
Examples:
blockquote{ border: 4px dashed; color: #508C19; background-color: #B4DBE6; }
-
You can change the background color of a whole page by applying the background-color property to the body element.
-
You can also use it for a marked up term:
<p>A <dfn class="glossary">baseline</dfn> is the imaginary line upon which characters sit.</p> .glossary{ color: #7C3306; background-color: #F2F288; }
It is another way of changing the transparency, just like what we did with RGBa color format.
opacity
-
Values: number (0 to 1)
-
Default: 1
-
Applies to: all elements
-
Inherits: no
-
Examples:
h1 {color: green; background: white; opacity: 0.25;}
Have you ever noticed that a link is often one color when you click on it and another color when you go back to that page? That is because, your browser is keeping track of which links have been clicked (or "visited", to use the lingo). The browser keeps track of another states too, such as whether the user's cursor is over an element (hover state), whether an element is the first of its type, the first or last child of its parent, and whether a form element has been checked or disabled, just to name a few.
In CSS, you can apply styles to elements in these states using a special kind of selector called a pseudo-class selector. It's an odd name, but you can think of it as though elements in a certain state belong to the same class. However, the class name is not in the markup -- it is something the browser keeps track of. So it is kinda like a class, it is pseudo-class.
Pseudo-class selectors are indicated by the colon(:) character. They typically go immediately after an element name, for example, li: first-child.
-
the most basic pseudo-class selectors target links (a elements) based on whether they have been clicked.
-
link pseudo-classes are a type of dynamic pseudo-class because they are applied as the result of the user interacting with the page rather than something in the markup.
-
:link, applies a tyle to unclicked (unvisited) links
-
:visited, applies a style to links that have already been clicked
-
Of course, you can set colors for both.
-
Examples,
a:link{ color: maroon; } a:visited{ color:gray; }
- another type of dynamic pseudo-classes targets element states that result from direct user actions.
- :focus, applies when the element is selected and ready for input;
- :hover, applies when the mouse pointer is over the element;
- :active, applies when the element (such a link or button) is in the process of being clicked or tapped;
Focus state
-
if you ever used a web form, then you should be familiar with how a browser visually emphasizes a form element when you select it. When an element is highlighted and ready for input, it is said to have "focus". The :focus selector lets you apply custom styles to elements when they are in the focused state.
-
in this example, when a user selects a text input, it gets a yellow background color to make it stand out from the other form inputs.
input:focus{background-color: yellow;}
Hover state
-
it targets elements while the user's mouse pointer is directly over them. Although you can use the hover state with any element, it is most commonly used with links to change their appearance and give the user visual feedback that an action is possible.
a:hover{ color: maroon; background-color: #ffd9d9; }
-
it is important to note that there is no hover state on touch screen devices such as smartphones and tablets, so this piece of feedback will be lost.
Active state
-
it applies styles to an element while it is in the process of being activated.
-
in the caes of a link, it is the style that is applied while it is being clicked or while a fingertip is in contact with it on a touch screen. This style may be displayed only for an instant, but it can give a subtle indication that something has happened.
a:active{ color: red; background-color: #ffd9d9;
}
There are also meny other pseudo-class selectors, we will see them later.
There are also four pseudo-elements that act as though they are inserting fictional elements into the document structure for styling. They are indicated by a double colon (::) symbol, but for better backward compatibility, use a single (:) as they are were defined in CSS2.
First letter and line
:first-line
-
this selector applies a style rule to the first line of the specified element. The only properties you can apply are:
- color
- font
- background
- word-spacing
- letter-spacing
- text-decoration
- vertical aligntext-transform
- line-height
-
Example
p:first-line {letter-spacing: 8px;}
:first-letter
-
this applies a style rule to the first letter of the specified element. The prperties you can apply are limited to:
- color
- font
- text-decoration
- text-transformvertical-align
- padding
- background
- margin
- line-height
- border
- float
- letter-spacing
- word-spacing
-
Example
p:first-letter {font-size: 300%; color: orange;}
Generated content with :before and :after
-
they are used to insert content before or after a specified element without actually adding the characters to the source document (this is called generated content in CSS).
-
Examples
p:before{ content: "Once Upon A Time"; font-weight: bold; color: purple; } p:after{ content: "The End"; font-weight: bold; color: purple; }
-
it targets elements based on their attributes. You can target attribute names or their values, which provides a lot of flexibility for selecting elements without needing to add a lot of class or id markup.
-
element[attribute]
; the simpe attribute selector targets elements with a particular attribute regardless of its value.- Example:
img[title]{border: 3px solid;}
- Example:
-
element[attribute="exact value"]
, the exact attribute value selector selects elements with specific value for the attribute. Values are case-sensitive and must be entered correctly in order to be recognized. . Example:img[title="first grade"] {border: 3px solid;}
-
element[attribute~="value"]
, the partial attribute value selector allows you to specify one part of an attribute value. So the example shows that the images with the tile value "first grade" and "second grade" would be selected.- Example:
img[title~="grade"] {border: 3px solid;}
- Example:
-
element[attribute|="value"]
, the hyphen-separated attribute value selector targets hyphen-separated values. This selector matches any link that points to a document written in a variation on the English language (en), whether the attribute value is en-us (American English), en-in (Indian English), en-au-tas (Australian English), and so on.- Example:
*[hreglang|="en"] {border: 3px solid;}
- Example:
-
element[attribute^="first part of the value"]
, the beginning substring attribute value selector matches elements whose specified attribute values start in the string of characters in the selector. This selector applies the style only to all images that are found in the /images/icons diretory (<img src="/images/icons...">).- Example:
img[src^="/images/icons"] {border: 3px solid;}
- Example:
-
element[attribute$="last part of the value"]
, the ending substring attribute value selector matches elements whose specified attribute values end in the string of characters in the selector.- Example:
a[href=".pdf"] {border: 3px solid;}
- Example:
-
element[attribute*="any part of the value"]
, the arbitrary substring attribute value selector looks for the provided text string in any part of the attriibute value specified. This rule selects any image that contains the word "Februray" somewhere in its title.img[title*="Februray"] {border: 3px solid;}
background-image: adding a background image to any element. Its primary job is to provide the location of the image file.
-
Values: url (location of image) | none | inherit
-
Default: none
-
Applies to: all elements
-
Inherit: no
-
Examples:
body{ bockgorund-image: url(star.gif); } blockquote{ background-image: url(dot.gif); padding: 2em; border: 4px dashed; }
-
The default behaviour of background image. Ihe image starts in the top lefthand corner and tiles horizontally and vertically until the entire element is filled (although you'll learn how to change that in a moment). Like background colors, by default tiling background images fill the area behind the content area, the extra padding space around the content, and extend to the outer edge of the border (if there is one).
-
If you provide both a background-color and a background-image to an element, the images will be placed on top of the color. In fact, it is recommended that you do provide a backup color that is similar in hue, in the event the image fails to download.
-
As usual for the web, keep the file size of backgorund images as small as possible.
background-position, it specifies the position of the origin image in the background. You can think of the origin image as the first image that is placed in the background from which tiling image extend.
-
Values: length measurement | percentage | left | center | right | top | bottom | inherit
-
Default: 0% 0% (same as left top)
-
Applies to: all elements
-
Inherits: no
-
Keyword positioning. The keyword values (left, right, top, buttom, and center) position the origin image relative to the edges of element's padding. If you provide only one keyword, the missing keyword is assumed to be center. Thus the
background-position: right
has the same effect asbackground-position: right center
. -
Length measurements. You can also specify the position by its distance from the top-left corner of the element using pixel measurements. The horizontal measurement always goes first.
background-position: 200px 50px;
-
Percentage. It is provided in horizontal/vertical pairs, with
0% 0%
corresponding to the top-left corner and100% 100%
corresponding to the bottom-right corner. It is important to note that the percentage value applies to both the canvas area and the image itself. For example, the 100% value places the bottom-right corner of the image in the bottom-right of the canvas. As with keywords, if you only provide one percentage, the other is assumed to be 50% (centered).background-position: 15% 100%;
-
Now we have learn to set the postion of the origin image as background, it will tile (both horizontally and vertically) to fill the background unless we set
background-repeat: no-repeat
. Moreover, settingbackground-repeat: repeat-y
will let it repeat vertically only.
background-size
, it specifies the size of backgorund image.
- Values: auto | contain | cover | length | percentage | inherit
- Defaults: auto
- Applies to: all elements
- Inherits: no
- If it shows two values, the first is horizontal size, the second is the vertical size.
-
auto
, the background image will retain the original size. -
cover
, it will resize the background image to make sure the element is fully covered. -
contain
, it will resize the background image to make sure it retains fully visible. - in pixels or percentages.
-
A gradient is a transition from one color to another, sometimes through multiple
background-attachment. When we scroll the page and watch what happens to the background image, as expected, it scrolls along with the document and off the top of the browser window, which is its default behavior. However, you can use background-attachment
property to free the background from the content and allow it to stay fixed in one position while the rest of the content scrolls
- Values: scroll | fixed | local | inherit
- Default: scroll
- Applies to: all elements
- Inherits: no
- Noticing that the local value, which was added in CSS3, makes a backgorund image scroll along with the content inside a scrolling element, independent of the browser viewpoint scroll. It is not supported in IE6 throught 8 or Firefoc as of this writing.
There are more CSS3 background properties to be explored.
CSS3 allows muitiple background images to be applied to a single element, and browsers are beginning to support them.
To apply multiple values for background-image
, put them in a list separated by commas. Additional background-related property values also go in comma-separated lists; the first value listed applies to the first image, the second value to the second and so on.
body{
backgorund-image: url(image1.png), url(image2.png), url(image3.png);
background-position: left top, center center, right bottom;
background-repeat: no-repeat, no-repeat, no-repeat;
... ...
}
A gradient is a transition from one color to another, sometimes through multiple colors. CSS3 introduces the ability to specify color gradients using CSS notation alone. Gradients can be applied anywhere an image may be applied: background-image, border-image, and list-style-image. We will focus on background-image in this chapter.
There are two types of gradients:
-
Linear gradients change colors along a line, from one edge of the element to the other.
-
the notation provides the angle of the line and one or more points along that line where the pure color is positioned (color stops).
-
for the angles, you set in degrees (n deg) or using keywords. e.g.,
0deg
,90deg
,180deg
;to top
,to right
,to bottom
,to left
; -
examples,
backgorund-image: linear-gradient(180deg, yellow, green); background-image: linear-gradient(to bottom, yellow, green);
-
in the next exmaple, the gradient now goes from left to right and includes a third color, orange, which appears 25% of the way across the gradient line. The 0% and 100% positions may be omitted.
background-image: linear-gradient(90deg, #e2e2e2, orange 25%, #fefefe);
-
-
Radial gradients start at a point and spread outward in a circular or elliptical shape.
-
the notation describes the shape (circle or ellipse; circle is default), the position of the center of the gradient (following the same syntax as background-position), and a size, specified as a radius length or a keyword that describes the side or corner where the last color should stop (closesr-side, farthest-side, closest-corner, farthest-corner, cover, contain).
-
example
background-image: radial-gradient(center, contain yellow green);
-
As we learned before, there are three ways to connect style sheets to a HTML document: inline with the style attribute, embedded with the style element, and as an external .css document linked to or imported into the document. In this section, we will go for the third option.
There are two ways to refer to an external style sheet: the link element and an @import rule.
-
it is the best to create a link element in the head of the document, as shown here
<head> <title> Title are required</title> <link rel="stylesheet" href="/path/stylesheet.css"> </head>
- with attributes rel="stylesheet" defining the linked document's relation to the current document, and href="url" defining the location of the .css file.
- you can include multiple link elements to different style sheets and they'll all apply. If there are conflicts, whichever one is listed last will override previous settings, due to the rule order and the cascade.
-
the other method for attaching an external style sheet to a document is to import it with an @import rule. The @import is another type of rule you can add to a style sheet, either in an external .css style sheet document, or right in the style element
<head> <style> @import url("/path/stylesheet.css"); p {font-face: Verdana;} </style> <title>Titles are required.</title> </head>
- the @import must go in the beginning of the style sheet before any selectors.
-
Modular Style Sheets, because you can compile information from multiple external style sheets, modular style sheets have become a popular technique for style management. Many developers keep styles they frequently reuse, such as typography treatment, layout rules, or form-related styles, in separated style sheets, then combine them in mix-and-match fashion using @import rules. Again, the @import rules need to go before rules that use selectors.
/*Content of clientsite.css*/ @import url("type.css") /*basic typography*/ @import url("form.css") /*from inputs*/ @import url("list-nav.css") /*navigation*/ bady {background: orange;} /*site-specific styles*/ ... more style rules ...
- The Element Box
- Specifying Box Dimensions
- Padding
- Borders
- Margins
position
- Assigning Display Roles
- Adding Drop Shadows to Boxes
Every element in a document, both block-level and inline, generates a rectangular element box.
-----------------------------Outer edge-------------------------------
- Margin Area -
- ---------------------Border (optional)--------------------------
- - Padding Area (optional) -
- - ------------------Inner edge-------------------------------
- - - Content Area -
- - -----------------------------------------------------------
----------------------------------------------------------------------
- Content Area. It is the core of the element box. The content area is indicated by text in a white box.
- Inner edges of the element box are the edges of content area. In real pages, the edge of the content area would be invisible.
- Padding is the area held between the content area and an optional border. Padding is optional.
- Border is a line (or stylized line) that surrounds the element and its padding. Borders are also optional.
- Margin is an optional amount of space added on the outside of the border. In real pages, margins are always transparent, allowing the bcakground of the parent element to show through.
- Outer edge. The outside edges of the margin area make up the outer edges of the element box. This is the total area the element takes up on the edge, and it indicates the width of the content area plus the total amount of padding, border, and margins applied to the element. In real pages, the edge of the margin is invisible.
Padding vs. Margin:
Padding goes around all four sides of the content and you can target and change the padding for each side with CSS. Margin is the space between the border and next element. The space outside the border between it and the other elements is the margin.
By default, the width and height of a block element is calculated automatically by the browser. It will be as wide as the browser window or other containing block element, and as tall as necessary to fit the content. However, you can use the width and height properties to make the content area of an element a specific width or height.
Unfortunately, setting box dimensions is not as simple as just dropping those properties in your style sheet. You have to know exactly which part of the element box you are sizing.
- Values: content-box | border-box
- Default: content-box
- Applies to: all elements
- Inherits: no
- Values: length measurement | percentage | auto | inherit
- Default: auto
- Applies to: block-level elements and replaced inline elements (such as images)
- Inherits: no
- Values: length measurement | percentage | auto | inherit
- Default: auto
- Applies to: block-level elements and replaced inline elements (such as images)
- Inherits: no
By default (that is, if you do not include a box-sizing rule in your styles), the width and height properties are applied to the content box. This is the way all current browsers interpret width and height values, but you can explicitly specify this behavior by setting box-sizing: content-box.
p{
background: #c2f670;
width: 500px;
height: 150px;
padding: 20px;
border: 2px solid gray;
margin: 20px;
}
// notice that the width of the visible element box ends up being 544 pixels. When you throw in 40 pixels of margin, the width of the entire element box is 584 pixels.
Knowing the resulting size of your elements is critical to getting layouts to behave predictably.
Since it is not the default browser behavior, you'll need to explicitly set border-sizing: border-box
in the style sheet.
p{
...
box-sizing: border-box;
width: 500px;
height: 150px;
...
}
In general practice, it is less common to specify the height of elements. It is more common in keeping with the nature of the medium to allow the height to be calculated automatically, allowing the element box to change based on the font size, user settings, or other factors. If you do specify a height for an element containing text, be sure to also consider what happens should the content not fit.
When an element is set to a size that is too small for its content, it is possible to specify what to do with the content that does not fit, using the overflow property.
- Values: visible | hidden | scroll | auto | inherit
- Default: visible
- Applies to: block-level elements and replaced inline elements (such as images)
- Inherits: no
-
visible
: it allows the content to hangout over the element box so that it all can be seen -
hidden
: it makes the content that does not fit getting clipped off and does not appear beyond the edges of the elements' content area -
scroll
, it is added to the element box to let users scroll through the content. Be aware that when you set the value toscroll
, the scrollbars will always be there, even if the content fits in the specified height just fine. -
auto
, it allows the browser to decide how to handle overflow. In most cases, scrollbars are added only when the content does not fit and they are needed.
Padding
is the space between the content area anf the border (or the place the border would be if one isn't specified). This is helpful to add padding to elements when using a background color or a border. It gives the content a little breathing room, and prevents the border or edge of the background from bumping right up against the text.
padding-top
, padding-right
, padding-bottom
, padding-left
- Values: length measurement | percentage | inherit
- Default: 0
- Applies to: all elements except table-row, table-row group, table-header-group, table-footer-group, table-column, and table-column-group
- Inherits: no
padding
- Values: length measurement | percentage | inherit
- Default: 0
- Applies to: all elements
- Inherits: no
- if providing 4 padding values, they should be in the order:
padding: top, right, bottom, left
; - if providing 3 values, the order is:
top right/left bottom;
- if providing 2 values, the order is:
top/bottom, right/left;
- if providing 1 value, it applies to all.
A border is simply a line drawn around the content area and its (optinoal) padding.
border-top-style
, border-right-style
, border-bottom-style
, border-left-style
- Values: none | dotted | dashed | solid | double | groove | ridge | inset | outset | inherit
- Default: none
- Applies to: all elements
- Inherits: no
border-style
- Values: none | dotted | dashed | solid | double | groove | ridge | inset | outset | inherit
- Default: none
- Applies to: all elements
- Inherits: no
- the way of using it is the same as above.
border-top-width
, border-right-width
, border-bottom-width
, border-left-width
- Values: length units | thin | medium | thick | inherit
- Default: medium
- Applies to: all elements
- Inherits: no
border-width
- Values: length units | thin | medium | thick | inherit
- Default: medium
- Applies to: all elements
- Inherits: no
border-top-color
, border-right-color
, border-bottom-color
, border-left-color
- Values: color name or RGB value | transparent | inherit
- Default: the value of the color property for the element
- Applies to: all elements
- Inherits: no
border-color
- Values: color name or RGB value | transparent | inherit
- Default: the value of the color property for the element
- Applies to: all elements
- Inherits: no
border-top
, border-right
, border-bottom
, border-left
- Values:
border-style
border-width
border-color
| inherit - Default: defaults for each property
- Applies to: all elements
- Inherits: no
border
- Values:
border-style
border-width
border-color
| inherit - Default: defaults for each property
- Applies to: all elements
- Inherits: no
Boxes with rounded corners have become a trendy style element over recent years.
border-top-left-radius
, border-top-right-radius
, border-bottom-right-radius
, border-bottom-left-radius
- Values: length measurement | inherit
- Default: 0
- Applies to: all elements
- Inherits: no
border-radius
- Values: 1, 2, 3, or 4 length percentage values
- Default: 0
- Applies to: all elements
- Inherits: no
Elliptical corners: so far, the corners we've made are sections of perfect circles, but you can make a corner alliptical by specifying two values: the first for the horizontal radius and the second for the vertical radius.
border-top-right-radius: 100px 50px;
If you want to use the shorthand property, the horizontal and vertical radii get separated by a slash (otherwise, they'd be confused for different corner values). The following example sets the horizontal radius on all corners to 60px and the vertical radius to 40px:
border-radius: 60px / 40px;
If you really want to see something really nutty, take a look at a border-radius shorthand property that specifies a different ellipse for each of the four corners. All of the horizontal values are lined up on the left of the slash in clockwise order (top-left, top-right, bottom-right, bottom-left).
border-radius: 36px 40px 60px 20px / 12px 10px 30px 36px;
We'll look at using the image of your choice. This property eliminates the need to cut up separate image files and add a bunch of useless markup to contain them.
border-image
: (we will not talk about it more, since it is rarely used right now)
- Values: border-image-source border-image-slice border-image-width border-image-outset border-image-repeat
- Default: defaults for each property
- Applies to: all elements except elements where
border-collapse
iscollapse
- Inherits: no
Margins keep elements from bumping into one another or the edge of the browser window. You can even use margins to make space for another column of content.
Adding a margin to the body element adds space between the page content and the edges of the browser window.
margin-top
, margin-right
, margin-bottom
, margin-left
- Values: length measurement | percentage | auto | inherit
- Default: auto
- Applies to: all elements
- Inherits: no
margin
- Values: length measurement | percentage | auto | inherit
- Default: auto
- Applies to: all elements except elements with table display types other than table-caption, table, and inline-table
- Inherits: no
It works the same way as the padding properties, including shorthands.
-
Collapsing margins. It is the top and bottom margins of neighboring elements collapse. This means that insead of accumulating, adjacent margins overlap, and only the largest value will be used.
- for example, given two paragraphs, if the top element has a bottom margin of 4 ems, and the following element has a top margin of 2 ems, the resulting margin space between elements DOES NOT add up to 6 ems. It will be 4 ems, the largest specified value.
-
Margins on inline elements. You can apply top and bottom margins to inline text elements, but it won't add vertical space above and below the element and the height of the inline will not change. However, if you apply left and right margins to inline text elements, margin space will be held clear before and after the text in the flow of the element, even if that element breaks over several lines. Just to keep thing interesting, margins on replaced elements, such as images, do render on all sides, and therefore do affect the height of the line.
-
Negative margins. It worth noting that it is possible to specify negative values for margins. When you apply a negative margins, the content, padding, and border are moved in the opposite direction that would have resulted from a positive margin value.
diaplay: It allows authors to specify how elements should behave in layouts.
- Values: inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | non e | run-in | compact | ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container
- Default: inline
- Applies to: all elements
- Inherits: yes
This property defines the type of element box an element generates in the layout. In addtion to the familiar inline and block diaplay roles, you can also make elements diaplay as list items or the various parts of a table. As you can see, there are a lot of roles.
There are quite common practices. For example, it is common to make li elements display as inline elements to turn a list into a horizontal bar, we may also make an otherwise inline a(anchor) element display as a block in orther to give it a specific width and height.
ul.navigation li {display: inline;}
ul.navigation li a {display: block;}
Another useful value for display is none, which removes the content from the normal flow entirely. Unlike visibility: hidden, which just makes the element invisible but holds the space it would have occupied blank, display: none removes the content, and the space it would have occupied is closed up.
One popular use of display: none is to prevent certain content in the cource document from displaying in specific area, such as when the page is printed or displayed on devices with small screens. For example, you could have a paragraph that appears when the document is printed, but it is not part of the page when it is displayed on a computer screen.
box-shadow
- Value: "horizontal offset" "vertical offset" "blur distance" "spread distance" color inset | none
- Default: none
- Applies to: all elements
- Inherits: no
The value of the box-shadow
property should seem familiar after working with text-shadow
: specify the horizontal and vertical offset distance, the amount the shadow should blur, and a color.
//it adds a simple box shadow, 6 pixels to the right and 6 pixels down, without blur or spread
box-shadow: 6px 6px #666
// adds a blur value of 5 pixels
box-shadow: 6px 6px 5px #666
// shows the effect of a 10-pixel spread value
box-shadow: 6px 6px 5px 10px #666
// you can make the shadow render inside the edges of the visible element box by adding the inset keyword to the rule. This makes it look like the element is pressed into the screen.
box-shadow: inset 6px 6px 5px #666
In this chapter, we will look at floating and positioning, the CSS methods for breaking out of the normal flow and arranging elements on the page. Floating an element moves it to the left or right, and allows the following text to wrap around it. Positioning is a way to specify the location of an element anywhere on the page with pixel precision.
In the CSS layout model, text elements are laid out from top to bottom in the order in which they appear in the source, and from left to right (in left-to-right reading languages). Block elements stack up on top of one another and fill the available width of the browser window or other containing element. Inline elements and text characters line up next to one another to fill the block elements.
When the window or containing element is resized, the block elements expand or contract to the new width, and the inline content reflows to fit.
Objects in the normal flow affect the layout of the objects around them. This is the behavior you've come to expect in web page --- elements do not overlap or bunch up. They make room for one another.
In this chapter we will be paying attention to whether elements are in the flow or removed from the flow. Floating and positioning change the relationship of elements to the normal flow in different ways.
float
: it moves the an element as far as possible to the left or right, allowing the following content to wrap around it. It is alfen used to create multicolumn layouts, navigation toolbars from lists, and table-like alignment without tables.
- Values:
left | right | none | inherit
- Default: none
- Applies to: all elements
- Inherit: no
We will demostrate this by applying the property on the img element. We can float the image to the right. This is shows how the paragraph and the contained image are rendered by default(top) and how it looks when the float property is applied(bottom).
// the markup
<p><img src="crown.gif" alt="">They went down, down, ...</p>
// the style sheets
img {
float: right;
margin: 10px;
}
In this way, we've gotten rid of a lot of wasted space on the page, but now the text is bumping right up against the image. Moreover, by adding a margin, we can add some space between the image element and the surrounding text.
Through steps above, we can see some behaviors of floated elements.
- A floated element is like an island in a stream. First and foremost, you can see that the image is removed from its position in the normal flow yet continues to influence the surrounding content. The subsequent paragraph text reflows to make room for the floated img element. One popular analogy compares floats to islands in a stream --- they are not in the flow, but the stram has to flow around them.
- Floats stay in the content area of the containing element. The floated image is placed within the content area (the inner edges) of the paragraph that contains it. It does not extend into the padding area of the paragraph.
- Margins are maintained. Margins are held on all sides of the floated area. In other words, the entire element box, from outer edge to outer edge, is floated.
-
For the inline text element
// for inline text element, the markup <p><span class="disclaimer"> Disclaimer: the existence of silver, gold, and diamond trees is not confirmed.</span> They went down, down, down, till at last they came to a passage..</p> // the style sheet span.disclaimer { float: right; margin: 10px; width: 200px; ... ... ... }
- Always provide a width for floated text elements. It is necessary to specify a width for floated text elements because without one, the content area of the box expands to its widest possible width (or, on some browsers, it may collapse to its narrowest possible width). Images have an inherent width, so we did not need to specify a width in the previous example (although we certainly could have).
- Floated inline elements behave as block elements. Notice that the margin is held on all four sides of the floated span text, even though top and bottom margins are usually not rendered on inline elements. This is because all floated elements bahave like block elements. Once you float an inline element, it follows the display rules for block-level elements, and margins are rendered on all four sides.
- Margins on floated elements do NOT collapse. In the normal flow, abutting top and bottom margins collapse(overlap), but for floated elements, the margins are maintained on all sides as specified.
-
For floating block elements, for example, a whole paragraph element is floated to the left.
// the markup <p>Once upon a time...</p> <p id="float">As he had a white skin, blue eyes, ...</p> <p>The fact was he thought then very ugly...</p> // the style sheet p#float { float: left; width: 200px; ... ... }
-
You must provide a
width
for floated block elements. If you don't, the width of the floated block will be set to auto, which fills the available width of the browser window or other containing element. There's not much sense of having a full-width floated box, because the idea is to wrap text next to the float, not start below it. - Elements do not float higher than their reference in the source. A floated block will float to the left or right relative to where it occurs in the source, allowing the following elements in the flow to wrap around it. It will stay below any block elements that precede it in the flow (in effect, it is "blocked" by them). That means you can't float an element up to the top corner of a page, even if its nearest ancestor is the body element. If you want a floated element to start at the top of the page, it must appear first in the document source.
-
You must provide a
If you are going to be floating elements around, it's important to know how to turn the text wrapping offanf get back to layout as usual. This is donw by clearing the element that you want to start below the float.
clear
: applied to prevent an element from appearing next to a floated element and forces it to start against the next available "clear" space below the float.
-
values:
left | right | both | none | inherit
- default: none
- applies to: block-level elements only
- inherits: no
- you use
clear: left;
to start the element below any elements that have been floated to the left. Smilarly, the valueright
makes the element clear all floats on the right edge of the containing block. If there are multiple floated elements, and you want to be sure an element starts below all of them, use theboth
value to clear floats on both sides.
It is fine to float multiple elements on a page or even within a single element. In fact it is only way to turn a list of links into a horizontal menu.
For example, we make a series of sequential paragraphs floated to the same side, the first three floats start stacking up from the left edge, but when there is not enough room for the fourth, it moves down and to the left until it bumps into something --- in this case, the edge of the browser window.
We can apply this more practical, like a navigation manu. There are various ways to converting it to a horizontal bar, but the primary staps in our floating example are as follows:
// 1. turn of the bullets, and set padding and margins to zero
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
// 2. float each list to the left so they line up, taking advantage of the multiple float behavior described ealier.
ul li {
float: left;
}
// 3. make the anchor elements in the list items (a) display as block elements so you can set the dimensions, paddings, margins, and other visual styles.
ul li a {
display: block;
... ...
}
// 4. then clear the element that comes after the menu in the document so it starts below the menu.
By default, floats are designed to hang out of the element they are contained in. That is just fine for allowing text to flow around a floated image. But sometimes it causes unwanted behaviors.
For example, sometimes the border stretched to contain all the content, but the floated image hangs right out the bottom.
And if you float all the elements in a container element -- as you might do to create a multicolumn layout -- there will be no elements remaining in the flow to hold the containing element open.
For example, the #container div
contains two paragraphs. The view of the normal flow (left) shows that the #container
has a background color and border that wraps around the content. However, when both paragraphs are floated, the element box for the #container
closes up to have a height of zero, leaving the floats hanging down below (you can still see the empty border at the top). This clearly is not the effect we are after.
But the fix to this problem is quite straightforward. One option is to float the containing element as well and give it a width of 100%.
#container {
float: left;
width: 100%;
...
...
}
The other common solution is to use overflow
property. You can also add width: 100%
, but note that if your container element has a border, the 100% width will make the border hang outside of the browser window.
- Making a Navigation Bar
- Using Floats to Create Columns
In the previous exercise, we specified margins in a combination of percentage valus and ems. It is common in contemporary web development, particularly for creating fluid layouts that respond to the size of the viewpoint. Some developers use percentages for all horizontal measurements so they are relative to the viewpoint size, but use ems for all vertical measurements because it is in keeping with the scale and the rhythm of lines of text. This techniques is a preference, not a requirement, but it is something to keep in mind.
position
: it indicates that an element is to be positioned and specifies which positioning method to use.
-
values:
static | relative | absolute | fixed | inherit
-
default:
static
- applies to: all elements
- inherits: no
static
- this is the normal positioning scheme in which elements are positioned as they occur in the normal document flow.
relative
- it moves the box relative to its original position in the flow. The distinctive bahavior of relative positioning is that the space the element would have occupied in the normal flow is preserved as an empty space.
absolute
- the absolutely positioned elements are removed from the document flow entirely and positioned with respect to the browser window or a containing element. Unlike relatively positioned elements, the space they would have occupied is closed up. In fact, they have no influence at all on the layout of surrounding elements.
fixed
- the element stays in one position in the window even when the document scrolls. Fixed elements are removed from the document flow anf positioned relative to the browser window (or other viewpoint) rather than another element in the document.
Each positioning method has its purpose, but absolute
positioning is the most versatile. With absolute positioning, you can place an object anywhere in the viewpoint or within another element. Absolute positioning can even be used to create multicolumn layouts, but it is more commonly used for small tasks, like positioning a search box in the top corner of a header. You can use absolute positioning to break an image or chunk out of its comtaining box, creating hanging indents or overlap effect. It is a handy tool when used careully and sparingly.
Once you established the positioning method, the actual position is specified with four offset properties.
top, right, bottom, left
-
values: length measurement | percentage |
auto
|inherit
-
default:
auto
- applies to: posiitoned elements (where position value is relative, absolute or fixed)
- inherits: no
The values provided for each of the offset properties defines the distance the element should be moved away from that respective edge. For example, the value of top
defines the distance the top outer edge of the positioned element should be offset from the top edge of the browser or other containing element. A position value for top
results in the element box moving down by that amount. Similarly, a positive value for left
would move the positioned element to the right (toward the center of the containing block) by that amount.
relative
positioning moves an element relativeto its original spot in the flow. The space it would have oppupied is preserved and continues to influence the layout of surrounding content.
em {
position: relative;
top: 30px;
left: 60px;
background-color: fuchsia;
}
The inline em
element is moved 30 pixels down from its initial position and 60 pixels to the right. Remember that the offset property values move the element away from the specified edge. Meanwhile, you can see the original space in the document flow is preserved, the surrrounding content is laid out as though the element were still there. Also, the overlap happen, because it is a posiitoned element, it can potentially overlap other element.
The empty space left behind by relatively positioned objects can be a little awkward, so this method is not used as often as absolute positioning. However, relative positioning is commonly used to create a "positioning context" for an absolutely positioned element.
Absolute positioning works a bit differently and is actually a more flexible method for accurately placing items on the page than relative positioning.
em {
position: absolute;
top: 30px;
left: 60px;
background-color: fuchsia;
}
In this case, the space once occupied by the em
element is now closed up, as is the case for all absolutely positioned elements. In its new positionm the element box overlaps the surrounding content. In the end, absolutely positioned elements have no influence whatsoever on the layout of surrounding elements. The most significent difference here, is the location of the positioned element. This time, the offset values position the em
element 30 pixels down and 60 pixels to the right of the top-left corner of the browser window.
However, the absolute positioning is not alway placed relative to the browser window, but to its nearest containing block. It just so happens that the nearest containing block is the root(html
) element, also known as the initial containing block, so the offset values position the em
element relative to the whole document.
The position and size of an element's box(ex) are sometimes calculated relative to a certain rectangle, called the containing block of the element. So it is critical to have an awareness of the containing block of the element you want to position. We sometimes refer to this as the positioning context.
The rules are basically:
- If the posiitoned element is not contained within another positioned element, then it will be placed relative to the initial containing block (created by the
html
element). - But if the element has an ancestor (i.e., is contained within an element) that has its position set to relative, absolute, or fixed, the element will be positioned relative to the edges of that element instead.
The most common way to make an element into a containing block is to set the position
to relative
, but do not move it with offset values. Also,
- the offset values apply to the outer edges of the element box (from margin edge to margin edge), and
- absolutely positoned elements always behave as block-level elements. For examle, the margins on all sides are maintained, even though this is an inline element. It also permits a width to be set for the element.
Now that you have a better feel for the containing block concept, let's take some time to get better acquainted with the offset properties. So far, we've only seen an element moved a few pixels down and to the right, but that's not all you can do.
pixels measurements
- As mentioned earlier, the positive offset values push the positioned element box away from the specified edge and toward the center of the containing block. If there is no value provided for a side, it is set to auto, and the browser adds enough space to make the layout work.
- In fact, the CSS specification provides a daunting set of rules for handling conflicts, but the upshot is that you should just be careful not to over-specify box properties and offsets. Gnerally, a width (factoring in optional padding, border, and margin) and one or two offset properties are all that are necessary to achieve the layout you're looking for. Let the browser take care of the remaining calculations.
percentage values
- You can also specify positions with percentage values. Be carefule when positioning elements at the bottom of the initial containing block (the
html
element`). Although you may expect it to be positioned at the bottom of the whole page, browsers actually place the element in the bottom corner of the browser window. Results may be unpredictable. If you want something positioned in a bottom corner of your page, put it in a containing block element at the end of the document source, and go from there.
- Absolute positioning
-
values: number |
auto
|inherit
-
default:
auto
- applies to: positioned elements
- inherits: no
As we've seen before, absolutely positioned elements overlap other elements, so it folows the multiple positioned elements have the potential to stack up on one another.
By default, elements stack up in the order in which they appear in the document, but you can change the stacking order with the z-index
property. The value of the z-index
property is a number (positive or nagative). The higher the number, the higher the element will appear in the stack. Lower elements and negative values move the element lower in the stack.
For example, take a look at three paragragh elements, each containing a letter image (A, B, and C), that have been positioned in a way that they overlap on the page.
// the markup
<p id="A"><img src="A.gif" alt="A"></p>
<p id="B"><img src="B.gif" alt="B"></p>
<p id="C"><img src="C.gif" alt="C"></p>
// the style sheet
#A { z-index: 10; ... ...}
#B { z-index: 5; ... ...}
#C { z-index: 1; ... ...}
By default, the paragraph "C" would appear on top because it appears last in the source. However, by assigning higher z-index
values to paragraphs "A" and "B", we can force them to stack in oue preferred order. Note that the values of z-index
do not need to be sequential, and they do not relate to anything in particular. All that matters is that higher number values position the element higher in the stack. If you want to guarantee that a positioned element always ends up on top, assign it a very high z-index
, such as z-index: 100;
.
For most part, fixed positioning works just like absolute positioning. The significant difference it that the offset values for fixed elements are always relative to the viewpoint, which means the positioned element stays put even when the rest of the page scrolls.
- Page Layout Strategies
- Multicolumn Layouts Using Floats
- Positioned Layout
- Top-to-Bottom Column Backgrounds
As you know, web pages appear on browsers of all sizes, from tiny phone screens to cinema displays. In addition, users can resize their text, which has an impact on the layout of the page. Over time several standard page layout approaches has emerged that address these issues in various ways:
- Fixed layouts stay put at a specific pixel width regardless of the size of the browser window or text size.
- Fluid (or liquid) layouts resize proportionally when the browser window resizes.
- Elastic layouts resize proportionally based on the size of the text.
- Hybrid layouts combine fixed and scalable areas.
Intro: they are created as a specific pixel width as determined by the designer. They allow the designer to control the relationship of page elements, alignment, and line lengths. This layout approach became popular due to the fact that folks have traditionally viewed the Web promarily on desktop monitors with ample real estate, and web designer were keen on reproducing designs that looked exactly the same on every screen. But time is changing.
When you design a new page to be a specific width, you need to decide a couple of things. First, you need to pick the width, usually based on common monitor resolution. You also need to decide where the fixed-width layout should be positioned in the browser window. By default, it stays on the left edge of the browser, withr the extra space to the right of it. You can also center the page, splitting the extra space over left and right margins which may make the page look as though it better fits the browser window.
One of our main concerns with using fixed layouts is that is the user's browser window is not as wide as the page, the content on the right edge of the page will be hidden. Although it is possible to scroll horizontally, it may not always be clear that there is more content there in the first place. In addtion, although the structure of the page doesn't change, if a user has text set to a very large size to make it easier to read, there may be very few words on a line and the layout may look awkward or break altogether.
Here are the pros and cons of the fixed-width strategy:
pros | cons |
---|---|
the layout is predictable and offers better control over line length. | content on the right edge will be hidden if the browser window is smaller than the page. |
it is easier to design and produce. | there may be an awkward amount of left over space on large screens. Line lengths may grow awkwardly short at very large text sizes. |
it behaves the way the majority of web pages behave as of this writing. But that may change as users visit the web primarily on devices other than the desktop. | takes control away from the user. |
Fixed-width layouts are created by specifying width values in pixel units. Typically, the content of the entire page is put into a div (often named "content", "container", "wrapper", or "page") that can then be set to a specific pixel width. This div may also be centered in the browser window.
The page area and columns within the page get wider or narrower to fill the available space in the browser window. In other words, they follow the default behavior of the normal flow. There is no attempt to control the width of the content or line breaks; the text is permitted to reflow as required and as is natural to the medium.
Fluid layouts are a cornerstone of the responsive web design technique. Now that web designers are coming to terms with the vast variaty of browser window and screen sizes, particularly those smaller than the traditional desktop monitor, many are moving to designs that flex to fill the browser width, whatever that might be.
Here are also pros and cons.
pros | cons |
---|---|
Fluid layouts keep with the spirit and nature of the medium. | On large monitors, line lengths can get very long and uncomfortable to read. |
They avoid potentially awkward empty space because the text fills the window. | They are less predictable. Elements may be too spread out or too scramped at extreme browser dimensions. |
On desktop browsers, users can control the width of the window and content. | It may be more difficult to archieve whitespace. |
No horizontal scrollbars. | There is more math involved in calculating measurements. |
Create a fluid layout be specifying width in percentage values. You may also simply omit the width
attribute. in which case the width
will be set to the dafault auto
setting and the element will fill the available wifth of the window or other containing element.
In the example of two-column layout, the width
of the each div has been specified as a percentage of the available page width (such as 70% and 25%).
div#main {
width: 70%;
margin-right: 5%;
float: left;
background: yellow;
}
dix#extras {
width: 25%;
float: left;
background: orange;
}
This approach marries resizable text with predictable line lengths. Elastic layouts expand or contract with the size of the text. If the user makes the text larger, the box that contains it expands proportionally. The result is that line lengths (in terms of workds or characters per line) stay the same regardless of the text size. This is an advantage over fluid layouts, where line lengths can get too long, and fixed layouts, where very large text may result in awkwardly few characters per line.
The full-page zoom feature offered by most current browsers has stolen some of elastic design's thunder. Now, all web pages appear to scale up proportionally, but elastic layouts can still address issues caused by users making changes to their default browser font size.
Here are the pros and cons
pros | cons |
---|---|
Provides a consistent layout experience while allowing flexibility in text size. | Images and videos do not lend themselves to automatic rescaling along with the text and the rest of the layout (but there are methods to achieve this). |
Tighter control over line lengths than liquid and fixed layouts. | The width of the layout might exceed the width of the browser window at largest text sizes. |
-- | Not as useful for addressing device and browser size variaty. |
-- | More complicated to create than fixed-width layouts. |
The key to elastic layouts is the em
, the unit of measurement that is based on the size of the text. For example, for an element with 16-pixel text, an em
is 16 pixels. It is common to specify font-size in em
s. In elastic layouts, the dimensions of containing elements are specified in em
s as well. That is how the widths can respond to the text size. For example, if the body text size is set to 16 pixels, and the page is set to 40em
, the resulting page width would be 640 pixels. If the user resizes the text up to 20 pixels, the page grows to 800 pixels.
Layouts that uses a combination of pixel, percentage, and em
measurements are sometimes called hybrid layouts
. In many scenarios, it makes sense to mix fixed and scalable content areas. For example, you might have a sidebar that contains a stack of ad banners that must stay a particular size. You could specify that sidebar at a particular pixel width and allow the column next to it to resize to fill the remaining space. You may remember that we created a page like that.
div#main{
width: auto;
position: absolute;
top: 0;
left: 225px;
background: yellow;
}
div#extras{
width: 200px;
position: absolute;
top: 0;
left: 0;
background: orange;
}
Floats are the primary tool for creating columns on web pages. As a tool, it ls flawed. The advantages that floats have over absolute positioning for layout are that they prevent content from overlapping other content, and they make it easier to keep footer content at the bottom of the page. The drawback is that they are dependent on the order in which the elements appear in the source, although there is a workaround using negative margins.
The following examples reveal the general strategy for approaching two- and three-column layouts using floats and should serve as a good head start toward implementing your own layouts.