Lecture: Introduction to CSS

advertisement

COM621 – Interactive Web

Development

Lecture 2 - Cascading Style Sheets

Web Styling

• We have seen how XHTML can be used to create content for a website, however we have not concerned ourselves with presentation.

• Most of the XHTML tags contain attributes that can define presentation style, however, using them have a few downsides:

XHTML element Styling

Downsides

• When styling using attributes for HTML tags, they need to be explicitly stated in each instance of the element in the page.

– When we need to change the look of the page, we would have to go through the source code line by line changing every instance of every attribute.

– As the amount of content increases, maintenance becomes more difficult.

• Attributes applied to XHTML elements allow only limited scope to adjust how they are displayed.

Style Sheets

• The concept of a style sheet did not originate on the web; it has been used extensively in computing for years now

• The most familiar application of style sheets off the web is the formatting styles used in word processors.

Cascading Style Sheets

• The term CASCADING STYLE SHEET (CSS) refers to a specific way in which browsers determine which styles apply to specific parts of the page.

• This method is called “The Cascade” and it’s from the cascade that CSS takes its name.

• CSS language was designed to be used primarily with HTML; therefore it is ideally suited for use in web design.

• The language is simple and flexible enough to encompass all common web presentation effects.

CSS in HTML

• There are 3 ways in which styling rules can appear in an HTML document:

– Linked,

– Embedded or

– Inline.

• The rules for each method are generally the same, but the way HTML and CSS work together depends on the method used.

Stylesheet Sample

• Stylesheets are text files saved with a .css

extension or sections of text embedded into web pages depending on your styling choice

Linked Stylesheets

• In order to assign a stylesheet to an HTML page, the

<link /> tag

• The link tag has 3 attributes that should be filled:

– href=“linkurl” – The URL of the resource (stylesheet file)

– rel=“linktype” – The forward link type (in CSS this is

“stylesheet”)

– type=“contenttype” – The internet content type (“text/css” for css)

• Example:

<link href="Pract2.css" rel="stylesheet" type="text/css" />

Embedded Stylesheets

• Embedded style sheets are useful when the rules apply only to the specific page in which they are located but not to the rest of the site.

• The <style></style> tag is used with only one required attribute: type which is set to

“text/css”

• The <style> tag needs to be located inside the

HEAD of the HTML document (nested)

Example:

Linked + Embedded

Linked Stylesheet

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Styling with CSS</title>

<link href="Pract2.css" rel="stylesheet" type="text/css" />

<style type="text/css">

<!--

Embedded Stylesheet span {color:green; text-decoration:overline;}

-->

</style>

</head>

Note the comments inside the <style> tag. This has to be done in order for the page to be XHTML validated

Inline Stylesheets

• Inline stylesheets make use of the style attribute of most HTML tags

• The attribute contains the “declaration” part of a CSS rule but not the “selector” (more on the following slides)

• Example

<p style="font-size:24px;">This is how a paragraph looks with different font size</p>

CSS Rules

• The building blocks of any stylesheet are the

CSS rules that compose it.

• Each rule is a single statement that identifies what should be styled and how those styles should be applied.

• Stylesheets are then composed of a list of rules, which the browser uses to determine what a page should look like.

CSS Rules

• A CSS rule consist of 2 sections: The selector(s) and the declaration(s) . A declaration is made up of a property and a value for that property, i.e.

– selector { property1: value; property2: value; }

• Note: CSS ignores extra spaces, so you can write your rules any way you want, i.e. the following will be the same rule as the previous one: selector { property1: value; property2: value;

}

CSS Rules

• The “selector” part of the rule tells which section of the document the rule covers.

• The simplest type of selector is a type selector that indicates a specific markup element, such as the <p> tag in HTML. You write a type selector by just giving the name of the element without the

<> brackets:

– p { property: value;}

• This rule will select the styling of all <p> tags.

CSS Rules

• The next part of the rule is the declaration.

• Declarations are enclosed in {} braces.

• Within the braces, the property name is given first, followed by a colon, and then a property value.

• several properties can be assigned to a selector by separating them using semi-colons.

• The entire rule is concluded by the ending brace.

body { background-color:yellow; color:#C30; }

CSS Rules

• Rules can also be combined if they have the same declaration and different selectors.

• Selector are combined by putting them in a list separated by commas:

– ul,ol,dl {background-color:#91FE0C}

CSS Comments

• Just like many other languages, CSS allows you to put comments in your stylesheet; to do that

, you need to enclose the comment inside the characters /* and */ as follows:

– /* place your comment here */

• Comments can appear anywhere in the stylesheet, even inside a rule.

Classess and IDs

• In addition to setting styles based on HTML elements, CSS allows for rules based on two optional attributes in HTML: class and id.

• Each of these can serve as the selector part of a

CSS rule and can be set on any visible HTML tag.

• Using the class and id selectors will really bring into life the <div> and <span> tags in HTML.

These two tags can be made to have nearly any effect and presentation.

HTML

Class Attribute

• The class attribute is used to define a related group of

HTML elements on a page. They may have the same function or role, but in a CSS context, it means they have the same style rules applied to them.

• To create a class, you simply have to give it a name. A class name can be nearly anything, but it has to be 1 word. (avoid using underlines, periods, and other nonalphanumerical characters when naming classes).

• Also note that a given HTML element can be part of 1 or more classes.

HTML

Class Attribute

• Example:

In this HTML we are

<body>

<div class="p1"> defining 4 classes named: p1,q2,r3 and j4

<h2 class="q2">Class Times</h2>

<p class="r3"> Classes are timetabled every Friday from

<span class="q2 j4">9.15</span> to <span class="q2 j4">2.05</span> in MG122</p>

</div>

</body>

In this example we can say that:

<div> is part of the p1 class

<h2> and <span> are part of the q2 class

<p> is part of the r3 class

<span> is also part of the j4 class

CSS

Class Selector

• After the classes have been defined in HTML, they can be used as a class selector in CSS

• Class selectors are indicated by a period (.) before the name of the class:

<style type="text/css">

<!--

.p1 {background-color:silver;}

.q2 {color:blue;}

.r3 {font-family:"Comic Sans MS", cursive;}

CSS

Class Selector

• Element selectors can be combined with class selectors; the result selects only those elements that are member of that particular class (leaving the other similar elements alone).

• This is done by putting the name of the element just in front of the period and then the class name: span.q2 {font-size:large;} p.r3 {color:green;}

All span elements with class q2

All p elements with class r3

CSS

Class Selector

• Several Classes can be combined together with a rule to select only elements that have those classes listed by separating them with periods (.):

.q2.j4 {font-family:Verdana, Geneva, sans-serif;}

-->

</style>

Applies to <span> that is part of both q2 and j4 class

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

/>

<title>Lecture2Classes</title>

<style type="text/css">

<!--

.p1 {background-color:silver;}

.q2 {color:blue;}

.r3 {font-family:"Comic Sans MS", cursive;} span.q2 {font-size:large;} p.r3 {color:green;}

.q2.j4 {font-family:Verdana, Geneva, sans-serif;}

-->

</style>

</head>

<body>

<div class="p1">

<h2 class="q2">Class Times</h2>

<p class="r3"> Classes are timetabled every Friday from <span class="q2 j4">9.15</span> to <span class="q2 j4">2.05</span> in

MG122</p>

</div>

</body>

</html>

Full Embedded

Style and Page

Browser Display

.p1 {background-color:silver;}

.q2 {color:blue;}

.r3 {font-family:"Comic Sans MS", cursive;} span.q2 {font-size:large;} p.r3 {color:green;}

.q2.j4 {font-family:Verdana, Geneva, sans-serif;}

HTML

ID Attribute

• The HTML attribute “id” is similar to the “class” attribute – it can be set on nearly any tag and can be used as a CSS selector – but it is much more restricted.

– Only 1 tag on a page can have a given id;

– It must be unique within the page and is used to identify just that element.

• An id’s attribute value has to begin with a letter and can be followed by letters, numbers, periods, underlines, hyphens, or colons; however if it is being used as a selector in CSS, it is safest to stick to just letters and numbers.

• Note: Case matters , so be consistent in the case of your id attributes.

<p id="bigf"> This whole paragraph need to have a big font</p>

CSS id Selector

• In CSS, an “id” selector is indicated by a #

(hash) before the value of the id. i.e.

<style type="text/css">

<!--

#bigf {font-size:36px;}

-->

</style>

Selectors

Universal

• In addition to type, class and id selectors, CSS also defines a universal selector. The universal selector applies to all tags and content within a page and is represented by an asterisk (*).

<style type="text/css">

<!--

* {color:purple;}

-->

</style>

Selectors

Descendant

• One of the most useful ways to group selectors together is to use a descendant selector.

• A descendant, in HTML and XML, is an element that is completely contained within another element’s content.

Movie Review

<html>

<head>

<title>Babe: Best Movie EVER</title>

<style type="text/css"> /* add style rules here */ </style> </head>

Example

<body>

<div class="header">

<h1> Movie Review: <cite> Babe</cite></h1>

<p>A Mini-Review by Joe H. Moviefan</p>

</div>

<div class="opinion">

<h2> The Best Movie <em>EVER</em></h2>

<h2> is a descendant of the <div> winning special effects -- who could ask for more? The clever writing and humorous contained within the two) adults. What a great movie!</p>

</div>

<div class="footer">

<p>What did you think? Mail me at

<a href="mailto:joe@example.com">Joe H. Moviefan.com!</a>

</p>

</div>

</body>

</html>

All of them are also descendants of the

<body>

Selectors

Descendants

• Descendant selectors define rules based on where a given tag appears within the page by combining together simple selectors, separated by spaces .

• p cite {color:white; background-color: black;}

• This rule changes the color of all <cite> tags contained within paragraphs.

• The order in which the tags are listed in the style rule is important, the outside tag must be written first. Also note that the <cite> inside <h1> is not styled by this rule, only the <cite> inside the <p> element.

Selectors

Descendants

• It is also important to keep in mind that a descendant selector means any descendant, not just an immediate child. This enables you to make rules that apply to any descendant element, no matter how deeply it’s nested.

• You can also combine section styles (set via class and <div>) with element-based type selectors, as well; for example the following code changes the font face and colours of <p> tags within the header section, but leaves the rest of the header alone, as well as the other paragraph tags that aren’t contained by something with the .header class:

• .header p {font-family:verdana, sans-serill; color:white; backgroundcolor:black;}

Pseudo Classes

• A pseudo-class selector is a selector based on a set of predefined qualities that an HTML element can possess.

These qualities function in practice similar to a class attribute on the element.

• No actual class attribute exist in the markup that correspond to these pseudo-classes; instead, they represent some aspect of the element to which they are applied, or even the state of the browser’s user interface relative to that element.

Pseudo Classes

• The pseudo-classes in CSS are:

Pseudo Classes Description

:active Elements that have been activated (such as active links)

:first-child The first child of an element

:focus

:hover

:lang()

Elements that have the focus (form fields receiving input)

Elements that are pointed at

:link

:visited

Styles for a specific language (examples: de,en,enca,en-uk,en-us,fr,jp,ru)

Unfollowed links

Previously visited links

Pseudo Classes

• Pseudo classes can’t stand alone in a style rule, as classes can, but most commonly they are used with elements as a tupe selector:

– :link {color:red;}

– a:link {color:red;}

• Both of these rules are valid, the former applies to any element that happens to be a link, whereas the latter rule covers only <a> tags.

• Note that in HTML only the <a> elements are links, so the rules mean the same thing

Pseudo Classes

• Pseudo classes can be combined with real classes or even other pseudo-classes putting them together with no spaces between, just the . and : indicators

• Example:

– <a href=“search.html” class=“nav”>Search the site</a>

– <a href=“http://maps.google.com class=“offsite”>Google Maps</a>

• CSS:

– a:link.nav {color:cyan;}

– a.offset:link {color:green;}

Pseudo Elements

• CSS defines four pseudo-elements - virtual elements created from their content in the document in relationship to a base element.

Pseudo-Element Description

:before Inserts something before an element

:after

:first-letter

:first-line

Inserts something after an element

The first letter of a block element

The first line of a block element

Pseudo Elements

:first-line & :first-letter

• :first-line and :first-letter select portions of another element, and these portions operate as if they were separate inline elements;

• However, only certain properties can be applied to these pseudo elements:

Pseudo Elements

:first-line & :first-letter

Property or Category :first-line :first-letter yes Background Properties

Border Properties

Color Properties

Font Properties

Margin Properties

Padding Properties clear float letter-spacing line-height text-decoration text-shadow text-transform vertical-align word-spacing yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes yes

<html>

<head>

<title>Fortune of Reversal</title>

<link type="text/css" rel="stylesheet" href="story-5.6.css">

</head>

<body>

<h1 id="storytitle">Fortune of Reversal</h1>

<div class="storybody">

<p>They dined on heaping platters of Szechuan chicken, of spicy beef, of shrimp and vegetables in some exotic dish without a name. Bits of food were passed from chopsticks to chopsticks, violating all known laws of Chinese cuisine etiquette. The tea flowed hot and fast that night, until the meal finally concluded itself.</p>

<p>"Thank you for dining here tonight," said the badgeless, anonymous waitress. She placed a small tray containing the check and two wrapped fortune cookies on the edge of the table, and hefted the empty plates one by one, forming a stack on the crook of her elbow.</p>

<p>"Absolutely delicious," declared Oliver as he pulled a card from his wallet and flicked it onto the bill. He picked up the two cookies, an afterthought. "Fortune cookie, my love?" he asked Amanda.</p>

</div>

</body>

</html>

Example

Example - CSS

#storytitle

{ font-family: Verdana; }

.storybody p

{ font-family: Arial; }

.storybody p:first-line

{background-color:silver;}

.storybody p:first-letter

{ font-size:xx-large; color:white; background-color:black; font-family:Verdana; }

Example

Browser

CSS Box Model

• The content of a web page is the information encoded within the HTML page, found between the opening and closing tags of the HTML markup.

• These tags define the structure of the content, a framework that gives meaning to the content; however, the presentation of the content is not defined by the HTML; instead, it is determined by CSS rules.

• The browser has default rules for <p> and <strong> tags, which say that a <p> tag is shown visually as a paragraph on lines of its own, with leading and trailing space, and that the <strong> is shown as bold text within that paragraph.

• Both tags are shown as display boxes, which is how CSS browsers deal with HTML.

Each HTML element corresponds to a box, although not all elements are shown on the screen. A display box is a rectangular shape on the screen that can contain text content, images, form controls, or other display boxes.

CSS Box Model

• The exact method by which HTML elements are shown as

CSS display boxes is called the visual formatting method. It tells the browser how they should show HTML content on the screen.

• The visual formatting model, markup elements are classified into two basic types: block and inline. The type of each HTML element is set by the HTML specification (for example <p> tags are block elements while <em> tags are inline elements). The type of a specific element can be changed with CSS, however, this often won’t be necessary; also, certain properties can be set only for block or inline elements.

CSS Box Model

• Block: A block element is one that is intended to be displayed as a distinct block of content, starting and ending with a new line. (examples of block elements are: <p>, <div>, <blockquote>, <table>, <br />, <ol>, and the

<h1> to <h6> tags.

• Inline:An inline element doesn’t begin and end lines; instead, it is contained within the flow of the text. Examples of inline tags include

<em>, <span>,<b>,<img>,<input>, and <a>.

• Inline elements flow one after another in a line, with no line breaks, horizontally across the page until the end of the available space is used up; then they just continue where they left off on the next line down.

CSS Box Model

• The way to change a type of an element is by using the display property. This property can take several values, however, for now we are only interested in the values: block and inline.

Setting the display property of an element changes the type of that element to the specified type.

The Box Model

Documents as trees

• Every web page is actually a tree of tags and content.

These type of trees are the same kind of data structures used in computer science.

• A tree is a way of representing information in a hierarchy of elements.

• The top element, called the root will be the <html> tag

• The <html> tag has two children: <head> and <body>; each of these children have children on their own.

• Each part of the tree is called a node. A node is either an element or some text.

The Box Model

Documents as trees

<html>

<head>

<title>Trees</title>

</head>

<body>

<h1>Trees, by <i>Joyce Kilmer</i></h1>

<p>

I think that I shall never see

<br />

A poem as lovely as a tree.

</p>

</body>

</html>

The Box Model

Documents as Trees

Documents as Boxes

• After an HTML document has been defined as a data tree, it can then be visually interpreted as a series of boxes

• This is probably the easier way for web developers to think of a page

• You can think of these boxes as containers that hold other boxes or that hold text values

Documents as Boxes

• The outer box is called the container box

• A block-containing box can hold other block boxes or inline boxes

• An inline-containing box can only hold inline boxes.

Display Box Properties

• After a browser has established that a box exists by building a tree and then filling in the box mode; it displays that box, either according to its own internal rules for displaying HTML or according to the style properties on that box

• In a way, all the CSS properties are box-displaying properties: They control how a box is displayed.

However, 3 properties define the edges of that box: The margin, the border and the padding.

Display Box Properties

• Virtually all documents elements can have borders with various styles, such as colour and width.

• Furthermore, The amount of space between the content of an element and its border

(known as padding) can be specified, as well as the space between the border and an adjacent element (known as the margin).

Fonts,

Colours and Effects

Fonts

• The font properties are among the most commonly used of the style-sheet properties.

Virtually all XHTML documents include text, which is often used in a variety of different situations. This creates a need for text in many different fonts, font styles, and sizes. The font properties allow us to specify these different forms.

Fonts,

Colours and Effects

Colours

• CSS provides two ways to define colour. The first is to use a color name, such as green or black; the second is to use a set of three RGB values, corresponding to the amount of Red, Green and Blue desired.

• The CSS specification recognizes 17 colours:

• Aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, orange, purple, red, silver, teal, white and yellow.

• Most browsers accept other colour names as well, such as pink, cyan and violet. However, until a future version of CSS adds those colours to the official specification, it’s best to avoid them as there is no guarantee that a browser will support them.

Fonts,

Colours and Effects

• To specify a colour in RGB notation, you need to know how much red, green and blue is contained in that colour. All RGB colours are measured based on a scale from 0 to 255. They are usually counted in hexadecimal.

• CSS offers four ways to present RGB values:

– Hexadecimal Notation: body {color:#CC66FF;}

– Short hex Notation: body {color:#C6F;}

– RGB numbers: body {color: rgb(204,102,255)

– RGB percentages: body {color: rgb(80%,40%,100%}

• Remember, when using colour to emphasize or present your pages, remember to take HCI considerations into account.

Fonts,

Colours and Effects

Special Text Effects

• CSS can also be used to produce text effects ranging from decorations to drop shadows.

• These can be used only on CSS elements that actually contain text; on anything else, they have no effect.

• Examples:

– Text-decoration (blink, line-through, overline, underline, none, inherit)

– Text-transform (capitalize, lowercase, uppercase, none, inherit)

– Text-Shadow

– Letter-spacing (normal, measurement, negative measurement, inherit)

– Word-spacing (normal, measurement, negative measurement, inherit)

– White-space(normal, nowrap, pre, pre-line, pre-wrap, inherit)

– Line-height (normal, measurement, multiplier, percentage, inherit)

Fonts,

Colours and Effects

• Background-Colour & Images

• Background colour as well as any other colourrelated property can be set as explained before, however there are two more property values available to background-colour:

– transparent: (Default) Whatever background already exists, will be shown

– inherit: Setting the value equal to that of the containing box. (inherit is used widely in other properties as well).

Background

Images

• In addition to use colours as backgrounds, you can also use images.

• This is similar to using the background attribute of HTML; the background attribute can be set only on the <body> tag, but CSS allows you to set a background image on any element.

• Usage:

– selector {background-image: url(image.gif);}

Background-Repeat

Property

• Background-repeat enables you to control whether or not the background image tiles across the screen.

Value repeat repeat-x repeat-y in-repeat

Effect tile horizontally and vertically tile only horizontally tile only vertically display the image only once, with no tiling.

Background-Position

Property

• Background images are placed in the upper-left corner of the element box it is styling.

• Background-position can be used to change the location of the initial image.

• A background position value consists of 2 size values or percentages: one indicating the horizontal position and the second indicating the vertical (only one value given set the horizontal)

– If values are used (30px, 4em etc.) they indicate where the image’s upper-left corner is to be placed.

– If percentages are used, they indicate how far over the image should be aligned (50% means that the center of the image

(horizontally and vertically) aligns with the center of the element being styled.

Background-Position

Property

• In addition or instead, word can also be used in this property:

Value Effect size size place the image at the specified location percentage percentage place the image proportionally top corresponds to 50% 0% left right corresponds to 0% 50% corresponds to 100% 50% bottom center top left corresponds to 50% 100% corresponds to 50% 50% corresponds to 0% 0%

Value top center top right

Effect same as top corresponds to 100% 0% left center same as left center center same as center right center bottom left same as right corresponds to 0% 100% bottom center same as bottom bottom right corresponds to 100% 100%

Background-attachment

Property

• Normally, images scroll with the rest of the page.

• The background-attachment property changes that

• This property can take 3 values:

– scroll (default)

– fixed (location of the image is relative to the whole page, not the element being styled)

– inherit (this property is not inherited unless explicitly stated using the inherit value.

Styling Forms

• The HTML language provides a <form> element that can be used to gather information interactively from the user, either for submission to the web server or for processing with JavaScript.

• These forms can be styled with CSS rules but variable browser support makes it an uncertain proposition.

Styling Form Elements

Examples

• Any style that can be used with box elements in HTML can be used with forms, labels, fieldsets and legends; these elements are well supported by web browsers.

Styling Form Elements

Examples

• In a text-box, the font, text-color and background color properties can be set using

CSS.

Styling Form Elements

Examples

• Buttons

• Checkboxes and Ratio Buttons

Box Sizing

& Offsets

• When laying out a page, it is not always enough to specify only where content should be placed. To create effective layouts, you need to set the size of display boxes.

• In HTML and CSS this is done with the height and width attributes.

• Exercise 2.8 will be used to demonstrate:

Box Sizing

& Offsets

• Set these initial rules on the stylesheet

Newspaper Display

Browser tries to determine the size and placement of each box and does not do very well

Width and Height

• When a browser displays a page like the one we just created, it determines the layout based on the space available and how large the content is. To start correcting the problems like the size and links box, we need to use the width and height properties.

• A CSS display box has two widths: The content width and the box width. The content width, is the width of the box’s content area; It is the area where the box’s content exists, within the padding, the border, and the margin; this is what is set by the width property.

• The box width is the width of the entire box, including left and right padding, the left and right border, and the left and right margin, as well as the content width. Content and box height are determined in the same way.

Width and Height

• The CSS properties width and height are used to control the size of the content width. To set the box’s width and height, you need to use the padding, border and margin values that add to the content width and height.

• The values can be measurements (such as Px or em) or they can be percentage value. (The percentage is based on the height or width of the parent box’s content area.

• Use the following CSS rules to fix the title wrapping problem of the 3 areas (play with the values until you are happy with the result)

Width and Height

Width & Height

• Note that when a width is set in the navigation bar, the text is forced to wrap,

• also notice that with these settings, there is extra space at the bottom of the navigation bar; the height has been set, and the space is reserved even if the content does not fill the space.

• Also note that there is no height for the #main

<div>, so the box ends where the text ends.

Minimum and Maximum

Dimensions

• Depending on the screen resolution, setting the width and height property might render boxes that are too small to maintain the style desired for the content.

• In order to solve this, some maximums and minimums could be placed on the sections allow for a more flexible design.

• The CSS properties used are called min/maxwidth/height.

Minimum and Maximum

Dimensions

• Incorporate these in your code

Resizing Browser

Minimum Horizontal

Overflow

• If a display’s box height hasn’t been set by the height property, the height is calculated automatically to take up enough room for all the content. If the height property is set and there is not enough space for all the text, then the text will overflow the box

– (set the height property of the #main to 128px.}.

Overflow

Overflow

• In order to correct this problem, the property overflow, can be set to something other that its default value (which is visible and creates the overflow effect). This property can be changed to:

– auto: The browser determines what to do with the overflowing content, choosing either scroll or visible.

– Hidden: Overflowing content is clipped and not displayed.

– Scroll: A scrollable box is used to provide access to all content.

– Visible: The overflowing content spills out of the box

– Inherit: use the value of overflow set on the containing box.

• Set the overflow to auto on #main

Relative Positioning

• Another way to align content is to float it. Floating boxes move to one side or another according to the value of the float property, and any following content flows around them in a liquid fashion.

• When a box is floated, it is positioned within it containing box’s content section. The floating box remains within the margin , border and padding of its containing box; is simply moves to the right or left side as appropriate. Any subsequent content is placed alongside the floating box for the length of that box.

Floating Content

To stop subsequent text from flowing around a floating element, you can set the clear property on the first element you don’t want to float. This moves that element down enough so that it doesn’t wrap around the floating box.

Relative Positioning

• CSS offers other ways to position boxes on the screen. A box’s location on the screen can be set by using the position property.

• A box that has been placed according to relative positioning

(position:relative) has been located relative to the position in which that box would normally appear, modified by an offset. This offset is designated by the top, left, right and bottom properties.

• The offset property values (top, bottom, left and right) accept both positive and negative values, percentages, inherit and automatic values.

Positive values will offset the box towards the inside (centre point of the content box) and negative values move the box away from the middle

(towards the outside).

Relative Positioning

<html>

<head>

<title>Three Boxes in a Row</title>

<style type="text/css">

.demobox { border: 3px solid black; width: 8em; font-family: Verdana, sans-serif; background-color: white; padding: 1em; margin: 0.5em; }

#mars { position: relative; left: 5em; top: 2em; }

</style>

</head>

<body>

<div class="demobox" id="earth">

Earth</div>

<div class="demobox" id="mars">

Mars</div>

<div class="demobox" id="jupiter">

Jupiter</div>

</body>

</html> with

Absolute & Fixed

Positioning

• Whenever an HTML element is included on a page, it generates a display box; normally, these boxes are placed one after another or within another box, based on the structure of the document and whether the box is an inline or block box.

• This is know as normal flow in the CSS specification. Whenever you move an element’s display box to a new location, you are disrupting the normal flow to create a new layout.

– The Float (clear) values for the alignment property moves the box out of the normal order to one side or the other, and subsequent content flows around it.

– Relative positioning (position property) preserves the normal content flow by reserving the appropriate amount of space for the relatively positioned element, and then moving it relative to that location.

Absolute & Fixed

Positioning

• There are two other types of positioning techniques that can be used: Absolute and fixed positioning. These methods also use the position property and the 4 offset properties

(top, left, bottom and right).

• When you set the position property to absolute, you are taking the element out of the normal flow of text and locating it relative to another box.

• This is called the containing block.

• The positioning element is placed relative to this containing block based on the offset properties.

Absolute & Fixed

Positioning

• The containing block is one of the parent boxes that contains the box being displayed – but it is not necessarily the immediate parent.

• The containing block is defined as the nearest ancestor to that box that has a position property value set on it. If none of the box’s ancestors has a position property set, then the containing block is the display box of the <body> tag.

• The easiest way to create a containing block context is to create a box and set is position to relative without any offset.

Absolute Positioning

• In absolute positioning, the containing block is initially set to be the box of the <body> tag

• absolutely positioned elements are placed relative to the rest of the page.

• If an ancestor box of an element is positioned

(with absolute, relative, or fixed positioning), that positioned box becomes the new containing block for absolute positioning.

<html>

<head>

<title>Three Boxes in a Row</title>

<style type="text/css">

.demobox { border: 3px solid black; width: 8em; font-family: Verdana, sans-serif; background-color: white; padding: 1em;}

#earth { position:absolute; left:50%; bottom:50%; }

#mars { position:absolute; right:50%; bottom:50%}

#jupiter { position:absolute; left:-50%; bottom:100%}

</style>

</head>

<body>

<div class="demobox" id="earth">Earth</div>

<div class="demobox" id="mars">Mars</div>

<div class="demobox" id="jupiter">Jupiter</div>

</body>

</html>

Example

Left-Right

#earth { position:absolute; left:0% ; bottom:50%; }

#mars { position:absolute; right:0% ; bottom:50%}

• Notice: Mars and Earth almost touch in the center. This is because they have values of 50% set for their right and left values, and 50% for their top and bottom values.

• However, the effects of these rules are not the same:

• 50% right and 50% left are two different positions

Top-Bottom

#earth { position:absolute; left:50%; bottom:50%; }

#mars { position:absolute; right:50%; top:50%}

Download