Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Programming, Building Internet Applications - Chris Bates.

Similar presentations


Presentation on theme: "Web Programming, Building Internet Applications - Chris Bates."— Presentation transcript:

1 Web Programming, Building Internet Applications - Chris Bates

2 Web Programming : Building Internet Applications Chris Bates CSE :

3 Introduction: WWW Difference between WWW & Internet HTML XML Difference between HTML and XML MIME

4 The WWW incorporates all of the Internet services -retrieve documents -view images -animation -Video -listen to sound file -speak and hear voice -view programs that run on practically any software in the world, -providing your computer has the hardware and software to do these things. World Wide Web

5 The Difference Between Internet & WWW The Internet is a massive network of networks, a networking infrastructure. It connects millions of computers together globally, forming a network in which any computer can communicate with any other computer as long as they are both connected to the Internet. Information that travels over the Internet does so via a variety of languages known as protocols. The World Wide Web, or simply Web, is a way of accessing information over the medium of the Internet. It is an information-sharing model that is built on top of the Internet. The Web uses the HTTP protocol, only one of the languages spoken over the Internet, to transmit data. Web services, which use HTTP to allow applications to communicate in order to exchange business logic, use the the Web to share information. The Web also utilizes browsers, such as Internet Explorer or Netscape, to access Web documents called Web pages that are linked to each other via hyperlinks. Web documents also contain graphics, sounds, text and video.

6 What is HTML Stands for "Hyper-Text Markup Language." This is the language that Web pages are written in. Also known as hypertext documents, Web pages must conform to the rules of HTML in order to be displayed correctly in a Web browser. The HTML syntax is based on a list of tags that describe the page's format and what is displayed on the Web page. The current version of HTML is HTML4.0. However, both Internet Explorer and Netscape implement some features differently and provide non-standard extensions.

7 What is XML XML stands for EXtensible Markup Language It is a markup language much like HTML It was designed to describe data XML tags are not predefined. You must define your own tags It uses a Document Type Definition (DTD) or an XML Schema to describe the data It with a DTD or XML Schema is designed to be self-descriptive

8 Difference between XML and HTML The main XML was designed to carry data. XML is not a replacement for HTML. XML and HTML were designed with different goals: XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks. HTML is about displaying information, while XML is about describing information.

9 Multipurpose Internet Mail Extensions, a specification for formatting non-ASCII messages so that they can be sent over the Internet. Many e-mail clients now support MIME, which enables them to send and receive graphics, audio, and video files via the internet mail system. In addition, MIME supports messages in character sets other than ASCII. There are many predefined MIME types, such as GIF graphics files and Post Script files. It is also possible to define your own MIME types. What is MIME

10 Web Development Tools many high-level tools exist for creating Web pages e.g., Microsoft FrontPage, Netscape Composer, Adobe PageMill, Macromedia DreamWeaver, HotDog, … also, many applications have "save to HTML" options (e.g., Word) for most users who want to develop basic, static Web pages, these are fine assembly language vs. high-level language analogy  may want low-level control  may care about size/readability of pages  may want to "steal" page components and integrate into existing pages  may want dynamic features such as scripts or applets so, why are we learning low-level HTML using a basic text editor?

11 Introduction to HTML

12 Getting Started.. What is HTML? How to create and View an HTML document? Basic HTML Document Format The HTML Basic tags HTML Protocol Headers Publishing Pages Contents

13 What the following term mean: 4Web server: a system on the internet containg one or more web site 4Web site: a collection of one or more web pages 4Web pages: single disk file with a single file name 4Home pages: first page in website Think about the followings before working your Web pages. 4Think about the sort of information(content) you want to put on the Web. 4Set the goals for the Web site. 4Organize your content into main topics. 4Come up with a general structure for pages and topics.

14 What is HTML? 4Telling the browser what to do, and what props to use. 4A serises of tags that are integrated into a text document. Tags are ; 4 surrounded with angle brackets like this * or. 4Most tags come in pairs * exceptions:,, tags … 4The first tag turns the action on, and the second turns it off.

15 4The second tag(off switch) starts with a forward slash. * For example, text 4can embedded, for instance, to do this: * Your text it won't work. * The correct order is Your text 4not case sensitivity. 4Many tags have attributes. * For example, centers the paragraph following it. 4Some browsers don't support the some tags and some attributes.

16 Basic HTML Document Format WENT'99 Went'99 WENT'99 Went'99 See what it looks like:

17 How to Create and View an HTML document? 1.Use an text editor such as Notepad to write the document. 2.Save the file as filename.html on a PC. This is called the Document Source. 3.Open Internet Explorer (or any browser) Off-Line 4.Click on File, Open File and select the filename.html document that you just created. 5.Your HTML page should now appear just like any other Web page in Netscape.

18 6.You may now switch back and forth between the Source and the HTML Document switch to Notepad with the Document Source make changes save the document again switch back to Internet Explorer click on RELOAD and view the new HTML Document switch to Notepad with the Document Source......

19  Tags in head ... -- contains information about the document ... -- puts text on the browser's title bar.

20 HTML Characteristics Just a Text File! + Portable + Human Readable/Writable Defines the Structure (not Appearance) of the Document  Client (Browser) defines the appearance Font preferences, window width, …  Pours into Browser (PDAs, Bigger/Smaller)

21 Document Structure My First Web Page A Paragraph of Text.

22 Nested Tags Like a tree, each element is contained inside a parent element Each element may have any number of attributes... bgcolor="white"...... other stuff...... This is some text!

23 Basic Tags My First Web Page A Paragraph of Text.

24 Basic Tags  Preamble which identifies content as HTML …  H1-6 where larger number means smaller heading  Includes vertical whitespace unlike

25 Basic Tags horizontal rule new line... bold... italicize text in between

26 Lists Unordered Lists Apples Oranges Ordered Lists One Two Can be nested o Apples 1. Fuji 2. Granny Smith o Oranges

27 Image Files JPEG  Best for photos  Public standard GIF  Best for simple images  Older standard PNG – Portable Network Graphics  Public standard replacement for GIF SVG – Scalable Vector Graphics  Series of drawing commands  Uses XML

28 Tables...... for each row... for each element in a row … for header row

29 Table Example row 1, cell 1 row 1, cell 2 row 2, cell 1 row 2, cell 2

30 Comments <!-- This paragraph, is also a comment... -->

31 Special HTML < →< > → > & → & → space

32 Anchor Tag (Links) Absolute HREFs specify fully qualified URLs. Yahoo! In this directory! In sub-directory a! Relative HREFs are relative to the directory containing the current HTML file.

33 Review: Client and Server User uses HTTP client (Web Browser) It has a URL (e.g. http://www.yahoo.com/) Makes a request to the server Server sends back data (the response) User clicks on the client side... request (URL) response (HTML, …)ClientServer

34 Client/Server Timeline

35 HTTP Request Structure

36 URL, URN, or URI? URN is location-independent resource identifier  urn:ietf:rfc:3187  urn:isbn:0451450523 URL is the location URI is the superset of URL & URN

37 URL Structure :// : @ : / ; ? #

38 Unsafe Characters Some Characters need to be encoded  ~ [ASCII: 126 (0x7E)]  SPACE [ASCII: 32 (0x20)]  % [ASCII: 37 (0x25)] Examples  http://www.bob.com/%7Ekelly/  http://www.bob.com/my%20home%20page.html  http://www.bob.com/100%25Crankiness.html

39 Empty-String Path http://www.yahoo.com Assume the path is "/" Client should send GET / HTTP/1.0\r\n\r\n

40 Relative Headers Client Side Given a URL in a file, if it is relative, will add base address to the relative URL Last requested path is http://foo.com/b/index.  in index.html see link</  base address is http://foo.com/b/ Client requests http://foo.com/b/a.html

41 Request Header GET / HTTP / 1.1

42 Request Header Example GET / HTTP/1.1 Host: localhost:8181 Connection: keep-alive Referer: http://localhost/~ronyeh/ User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125 Accept: */* Accept-Encoding: gzip, deflate;q=1.0, identity; q=0.5, *;q=0 Accept-Language: en-us, ja;q=0.62, de-de;q=0.93

43 General Headers Used by clients & servers Seen in both requests and responses Date: Tue, 3 Oct 2004 02:16:00 GMT Connection: keep-alive

44 Request Headers Client-IP: 192.168.1.12 Host: hostmachine.com Referer: http://wherefrom.com/ User-Agent: Mozilla/5.0 UA-OS If-Modified-Since

45 Request Headers Accept: */* Accept: text/html Accept-Language: en-us, ja Accept-Encoding: gzip

46 HTTP Response Structure

47 Example Response

48 HTTP Server Response Codes 200 OK 3XX -- Minor Client Error  301 -- File Moved Permanently  302 -- Moved Temporarily  304 -- Not Modified 4XX -- Major Client Error  400 -- Syntax Error  401 -- Unauthorized  403 -- Forbidden, Permission Denied  404 -- Not Found!

49 HTTP Server Response Codes 5XX -- Server Errors  500 -- Internal Server Error  503 -- Service Unavailable

50 General Headers Used by clients & servers Seen in both requests and responses Date: Tue, 3 Oct 1974 02:16:00 GMT Connection: close

51 Server Response Headers Server: GWS/2.1 Content-Length: 2136 Content-Type: text/html Location Expires Last-Modified

52 MIME Multipurpose Internet Mail Extensions type, subtype, & optional parameters type/subtype; param1=value1

53 MIME types application/* audio/* image/*  image/jpeg  image/tiff text/*  text/xml  text/rtf  text/html  text/plain video/*  video/quicktime  video/mpeg  video/x-msvideo

54 Pages with Multiple Types Each entity (ex. image) is standalone HTTP request  Page with many pictures creates many connections Each response therefore has appropriate MIME settings

55 Mapping URL Path Server can map URLs to any place on the file system. Doesn't have to be under the Document Root. It's the server's choice!!! User names  ~kashaw May map to /users/kashaw/WWW /a/b/ => maps to a default file  index.html, default.html, index.htm, index.shtml /a/b/ => if default file doesn't exist, may list the directory's files

56 Trailing Slash What if Client asks for /a/b Say file b doesn't exist Utilize the 301 Redirect to /a/b/ Client re-does request What happens if server does NOT issue 301, but gives the client the right file anyways?

57 Advanced Topics Redirection Caching Performance HTTP 1.1

58 When NOT to Redirect Client requests /a/b/  Server maps to /a/b/index.html and sends back html file  A Link Client takes base address /a/b/ concatenates with c.html Client requests /a/b/c.html which is correct!

59 When to Redirect URL missing trailing slash  No file named /class/cs193i  But, directory named /class/cs193i/ If Redirect did NOT happen  Client thinks base address is /class/  a relative href=”schedule.html” in cs193i will be mapped by client to /class/schedule.html  Server will return 404 Not Found

60 Why Redirect? Reliability (Find Live Hosts) Minimize Delay (Find Shortest Path) Conserve Network Bandwidth (Spread out Requests Geographically) Load Balancing (Distribute Requests Temporally)

61 Load Balancing Example GET / HTTP/1.1 Host: www.goldenretrievers.com HTTP/1.1 302 Found Date: Wed, 10 July 2004 16:46:17 GMT Location: http://c.goldenretrievers.c om

62 Load Balancing Example

63 Redirection Tradeoffs HTTP Redirection  Every request initially goes through the www.goldenretrievers.com machine  Must Customize www Web Server Alternative: DNS Redirection  DNS server decides which IP address to return (from a list of OK IP Addrs) Alternative: Hardware Redirection  NAT Box! Packet rewriting!

64 Caching Motivation Redundant Data Transfer Network Bandwidth Bottlenecks Server Demand Distance Delays (Latency)

65 Adding Caching Web Cache Server < Traffic

66 Hit, Miss, Revalidate

67 Revalidate Options Check via If-Modified-Since...Not Modified  Suffers from 2X latency between cache & server Just assume, and have a timeout, refresh cache automatically

68 Request / Response Timeline Time

69 Web Pages w/ Multiple Requests Time

70 Persistent Connections

71 Pipelining Connection: Keep-Alive

72 Persistent Connections HTTP 1.0 -- Connections close by Default  No need for Content-length, end signaled by EOF (in-band signal) HTTP 1.1 -- Persistent by Default  Must use Content-length

73 Chunked-Transfer Encoding Problem: Content-length costly for server Solution  Server omits Content-Length  Transfer-encoding: chunked  Send Data in Chunks, Prefixed by length in Hex End is marked with Chunk Length 0 (in band signal like in POP)

74 Publishing pages Viewing your pages via the internet  Send pages to a web server  How a page is distributed  Server space maintenance  Common ways (protocols) of sending pages to a web server FTP SSH Through a mapped drive

75 Publishing pages Sending pages via FTP to a web server  File Transfer Protocol  Plain-text data transfer  Microsoft’s FTP client ftp://username:password@www.ftpserver.com ftp://username@www.ftpserver.com  Other FTP clients WS_FTP CuteFTP

76 Publishing pages Exercise: Publish pages to usiweb.usi.edu through an FTP client  Go to your desktop  Open “My Computer” or “Internet Explorer”  Type in the following URL into the address field: Oakland’s ftp address

77 Publishing pages Sending pages via SSH  Secure Shell  Encrypted data transfer  More secure than FTP  SSH used with www.oakland.edu for off- campus accesswww.oakland.edu  SSH clients SSH Secure Shell PuTTY (Free Win32 SSH client)

78 Publishing pages Sending pages through a mapped drive  Method used to publish on campus to www.oakland.edu. Normally labeled “H:” or “the H drive”. www.oakland.edu

79 Publishing pages Creating a mapped drive for www.usi.eduwww.usi.edu  Make sure you have access to on the web server  If not: Have your fiscal agent send an e-mail to Web Services approving access  Go to your computer’s desktop  Right click on the “My Computer” icon  Select “Map Network Drive…”  Enter Q: as the drive letter  Enter \\www\www_usi as the folder\\www\www_usi  Click on Finish or OK  Traverse to your folder you have access to using FrontPage or another web publishing application

80

81

82 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language (a scripting language is a lightweight programming language) A JavaScript consists of lines of executable computer code A JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Everyone can use JavaScript without purchasing a license

83 JavaScript is not Java By now you should have realized that you already know a great deal of JavaScript  So far we have talked about things that are the same as in Java JavaScript has some features that resemble features in Java:  JavaScript has Objects and primitive data types  JavaScript has qualified names; for example, document.write("Hello World");  JavaScript has Events and event handlers  Exception handling in JavaScript is almost the same as in Java JavaScript has some features unlike anything in Java:  Variable names are untyped: the type of a variable depends on the value it is currently holding  Objects and arrays are defined in quite a different way  JavaScript has with statements and a new kind of for statement

84

85

86

87 Elements of JavaScript Variables Arrays Functions

88 Primitive data types JavaScript has three “primitive” types: number, string, and boolean  Everything else is an object Numbers are always stored as floating-point values  Hexadecimal numbers begin with 0x  Some platforms treat 0123 as octal, others treat it as decimal Strings may be enclosed in single quotes or double quotes  Strings can contains \n (newline), \" (double quote), etc. Booleans are either true or false  0, "0", empty strings, undefined, null, and NaN are false, other values are true

89 Variables <!-- definition of variables var num_car= 25; var passenger_per_car= 3; //calculation of total number of people var total_passenger= num_car * passenger_per_car Alert(total_passenger); // end of script -->

90

91 Variables Variables are declared with a var statement:  var pi = 3.1416, x, y, name = "Dr. Dave" ;  Variables names must begin with a letter or underscore  Variable names are case-sensitive  Variables are untyped (they can hold values of any type)  The word var is optional (but it’s good style to use it) Variables declared within a function are local to that function (accessible only within that function) Variables declared outside a function are global (accessible from anywhere on the page)

92 Operators, I Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it Arithmetic operators: + - * / % ++ -- Comparison operators: = > Logical operators: && || ! ( && and || are short-circuit operators) Bitwise operators: & | ^ ~ > >>> Assignment operators: += -= *= /= %= >= >>>= &= ^= |=

93 Operators, II String operator: + The conditional operator: condition ? value_if_true : value_if_false Special equality tests:  == and != try to convert their operands to the same type before performing the test  === and !== consider their operands unequal if they are of different types Additional operators (to be discussed): new typeof void delete

94 Comments Comments are as in C or Java:  Between // and the end of the line  Between /* and */ Java’s javadoc comments, /**... */, are treated just the same as /*... */ comments; they have no special meaning in JavaScript

95 Statements, I Most JavaScript statements are also borrowed from C  Assignment: greeting = "Hello, " + name;  Compound statement: { statement ;...; statement }  If statements: if ( condition ) statement ; if ( condition) statement ; else statement ;  Familiar loop statements: while ( condition ) statement ; do statement while ( condition ); for ( initialization ; condition ; increment ) statement ;

96 Statements, II The switch statement: switch ( expression) { case label : statement ; break; case label : statement ; break;... default : statement ; } Other familiar statements:  break;  continue;  The empty statement, as in ;; or { }

97 Exception handling, I Exception handling in JavaScript is almost the same as in Java throw expression creates and throws an exception  The expression is the value of the exception, and can be of any type (often, it's a literal String) try { statements to try } catch ( e ) { // Notice: no type declaration for e exception-handling statements } finally { // optional, as usual code that is always executed }  With this form, there is only one catch clause

98 Exception handling, II try { statements to try } catch ( e if test1 ) { exception-handling for the case that test1 is true } catch ( e if test2 ) { exception-handling for when test1 is false and test2 is true } catch ( e ) { exception-handling for when both test1and test2 are false } finally { // optional, as usual code that is always executed } Typically, the test would be something like e == "InvalidNameException"

99 Object literals You don’t declare the types of variables in JavaScript JavaScript has object literals, written with this syntax:  { name1 : value1,..., nameN : valueN } Example (from Netscape’s documentation):  car = {myCar: "Saturn", 7: "Mazda", getCar: CarTypes("Honda"), special: Sales} The fields are myCar, getCar, 7 (this is a legal field name), and special "Saturn" and "Mazda" are Strings CarTypes is a function call Sales is a variable you defined earlier  Example use: document.write("I own a " + car.myCar);

100 Three ways to create an object You can use an object literal:  var course = { number: "CIT597", teacher="Dr. Dave" } You can use new to create a “blank” object, and add fields to it later:  var course = new Object(); course.number = "CIT597"; course.teacher = "Dr. Dave"; You can write and use a constructor:  function Course(n, t) { // best placed in this.number = n; this.teacher = t; }  var course = new Course("CIT597", "Dr. Dave");

101 Arrays var score = new Array(3); score[0] = 35 score[1] = 56 score[2] = 10 Alternative : var score = new Array(35,56,10); sum=score[0]+score[1]+score[2]; alert(sum) ;

102 Array literals You don’t declare the types of variables in JavaScript JavaScript has array literals, written with brackets and commas  Example: color = ["red", "yellow", "green", "blue"];  Arrays are zero-based: color[0] is "red" If you put two commas in a row, the array has an “empty” element in that location  Example: color = ["red",,, "green", "blue"]; color has 5 elements  However, a single comma at the end is ignored Example: color = ["red",,, "green", "blue”,]; still has 5 elements

103 Four ways to create an array You can use an array literal: var colors = ["red", "green", "blue"]; You can use new Array() to create an empty array:  var colors = new Array();  You can add elements to the array later: colors[0] = "red"; colors[2] = "blue"; colors[1]="green"; You can use new Array( n ) with a single numeric argument to create an array of that size  var colors = new Array(3); You can use new Array( …) with two or more arguments to create an array containing those values:  var colors = new Array("red","green", "blue");

104 The length of an array If myArray is an array, its length is given by myArray.length Array length can be changed by assignment beyond the current length  Example: var myArray = new Array(5); myArray[10] = 3; Arrays are sparse, that is, space is only allocated for elements that have been assigned a value  Example: myArray[50000] = 3; is perfectly OK  But indices must be between 0 and 2 32 -1 As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]

105 Arrays and objects Arrays are objects car = { myCar: "Saturn", 7: "Mazda" }  car[7] is the same as car.7  car.myCar is the same as car["myCar"] If you know the name of a property, you can use dot notation: car.myCar If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car.["my" + "Car"]

106 Array functions If myArray is an array,  myArray.sort() sorts the array alphabetically  myArray.sort(function(a, b) { return a - b; }) sorts numerically  myArray.reverse() reverses the array elements  myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length  myArray.pop() removes and returns the last element of the array, and decrements the array’s length  myArray.toString() returns a string containing the values of the array elements, separated by commas

107 The for…in statement You can loop through all the properties of an object with for ( variable in object ) statement ;  Example: for (var prop in course) { document.write(prop + ": " + course[prop]); }  Possible output: teacher: Dr. Dave number: CIT597  The properties are accessed in an undefined order  If you add or delete properties of the object within the loop, it is undefined whether the loop will visit those properties  Arrays are objects; applied to an array, for…in will visit the “properties” 0, 1, 2, …  Notice that course["teacher"] is equivalent to course.teacher You must use brackets if the property name is in a variable

108 The with statement with ( object ) statement ; uses the object as the default prefix for variables in the statement For example, the following are equivalent:  with (document.myForm) { result.value = compute(myInput.value) ; }  document.myForm.result.value = compute(document.myForm.myInput.value); One of my books hints at mysterious problems resulting from the use of with, and recommends against ever using it

109 Function <!-- hide me function announceTime( ) { //get the date, the hour, minutes, and seconds var the_date = new Date(); var the_hour = the_date.getHours(); var the_minute = the_date.getMinutes(); var the_second = the_date.getSeconds(); //put together the string and alert with it var the_time = the_hour + ":" + the_minute + ":" + the_second; alert("The time is now: " + the_time); } // show me -->...

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136 Cascading Style Sheets Chapter Four

137 What are they? A set of style rules that tell the web browser how to present a web page or document. Cascading Style Sheets  Standard set by the W3C for managing the formatting information of HTML documents  A single piece of formatting information is called a style  CSS separates document content from its appearance

138 Using Style Sheets - Pro 1.Build from the ground up to replace traditional Web design methods 2.Faster download times because Style sheets can be cached by the user agent, reducing the size of files downloaded 3.Shorter development time 4.Greater control over the typography in a Web page

139 Using Style Sheets – Pro (cont) 5.It's easy to write 6.Improvements in accessibility 7.Print designs as well as Web page designs 8.Better control over the placement of elements in Web page.Controlling the look with style sheets means that an entire site can be changed with a few changes on one file - a style sheet

140 Using Style Sheets – Pro (cont) 9.The design of Web pages is separated from the content 10.Better search engine rankings

141 Using Style Sheets - Con Sites need much more planning for effective use Learning curve can be steep Much more testing required in all possible browsers

142 A Brief History of HTML and CSS Separating Style from Structure  Mixing display instructions and structural information: Adds to complexity of code Inefficient mechanism for handling display characteristics of multi-page Web sites Limits cross-platform compatibility of content limits diversity of web devices

143 What are they? Web page CONTENT STYLE

144 CONTENT STYLE What are they? Web page CSS styles are created using name/value pairs separated by a colon Name portion refers to a specific CSS style attribute known as a property

145 Sample Style Sheet

146 What Can I Change? Font Stuff - size, family, weight, variant (small caps) white space, letter spacing, line height Spacing - margin, padding, Alignment - right, left, center, top, bottom, center Color - font, background, hover Text - alignment, indent, decoration Containers - size, placement, alignment, color, use And more…

147 Single CSS to many Web Pages CSS

148 Many CSS to Single Web Page CSS Physical layout Headings Body Text

149 Devices CSS Content PRINT MOBILE BROWSER Different CSS for Different Type of Browser

150 The Box Model

151 Example

152 Understanding Boxes

153 Parents and Children An object that contains another is the parent of the object it contains An object contained by another is the child of the object containing it

154 Types of CSS External Embedded Imported Inline

155 External Connection made via the LINK tag Use the optional TYPE attribute to specify a media type  type/css

156 Internal/Embedded Style characteristics are embedded in the HEAD section of the webpage Perhaps best used when a single page requires a unique style sheet

157 Imported Allows for using style sheets from other sources Must be included at the beginning of the style sheet using the @import statement Other CSS rules can be included

158 Inline Least flexible Requires each element to be tagged if you want them to appear differently Looses the advantage of using CSS

159 Inserting a CSS External sheet

160 Inserting a CSS Internal/embedded sheet hr { color: navy} body {margin-left: 20px}

161 Inserting a CSS Internal/embedded sheet for older browsers <!-- hr { color: navy} body {margin-left: 20px} -->

162 Inserting a CSS Inline This is a paragraph

163 Using multiple sheets You can use multiple sheets to define the style of your document Internal styles will override external styles, if they are duplicated

164 Using multiple sheets h3 {color: red; text-align: right; font-size: 8pt} (external CSS) h3 {text-align: center; font-size: 20pt} (internal CSS) will yield

165 Using multiple sheets h3 {color: red; text-align: right; font-size: 8pt} (external CSS) h3 {text-align: center; font-size: 20pt} (internal CSS) will yield h3 {color: red; text-align: center; font-size: 20pt }

166 Sheet weight or Precedence Author’s style sheet User’s style sheet Browser’s style sheet Greatest weightLeast weight

167 Sheet weight or Precedence

168 Understanding the Cascade Cascading  Determining rule weight by specificity Rules with more specific selectors take precedence over rules with less specific selectors  Determining rule weight by order Based on order of rule within style sheet Those listed later take precedence over those listed earlier in the style sheet

169 Understanding the Cascade Inheritance  Based on hierarchical structure of documents CSS rules inherit from parent elements to child elements: thus elements will inherit style rules from elements unless a style rule is specifically set for the element

170 Basic CSS Syntax

171 Three parts:  selector  property  value selector {property: value} } declaration

172 Basic CSS Syntax selector {property: value} selector: the basic HTML element tag you wish to define body

173 Basic CSS Syntax selector {property: value} property: the attribute of the selector that you wish to change body {color

174 Basic CSS Syntax selector {property: value} value: the particular markup value for that attribute body {color : black}

175 Basic CSS Syntax If the value has multiple words, put the value in quotes p {font-family: “sans serif” }

176 Basic CSS Syntax You can specify multiple properties to a single selector. Properties must be separated by a semicolon. P { text-align: left; color: red }

177 Basic CSS Syntax To make properties more readable, put each on a separate line. p { text-align: center; color: navy; font-family: arial }

178 Basic CSS Syntax Selectors can be grouped so that a common property can be specified h1,h2,h3,h4,h5,h6 { color: yellow } This is a level 1 heading This is a level 2 heading

179 Basic CSS Syntax Selectors can be descendants P B { color: yellow } In this example, only those elements within a element would be yellow This would be yellow This would not be yellow

180 CSS Syntax - class The class selector allows you to create different styles for the same HTML element. p.right { text-align: right } p.center { text-align: center }

181 CSS Syntax - class p.right { text-align: right } This paragraph will be right aligned. Note: the class name must be in quotes inside the opening tag

182 CSS Syntax - class This is improper use of the class selector: This paragraph will be right aligned. Only one class selector can be included inside the tag

183 CSS Syntax - class You can also create a class selector free of a tag name if you want all tags that have that class to be formatted the same..center { text-align: center } Any tag with a “center” class will be aligned center

184 CSS Syntax - class.center { text-align: center } This heading will be centered So will this text

185 CSS Syntax - id While the class selector can apply to several different elements, the id selector can only apply to one, unique element. p#para1 { text-align: center; color: green }

186 CSS Syntax - id p#para1 { text-align: center; color: green } This text would be centered and green

187 CSS syntax - can be used with the CLASS attribute to create customized block-level elements  Declare it in the style rule: DIV.introduction {font-size: 14pt; margin: 24 pt;}  Apply the style rule in the document: This is the introduction to the document

188 CSS syntax - can be used with the CLASS attribute to create customized inline elements  Declare it in the style rule: SPAN.logo {color: white; background-color: black;}  Apply the style rule in the document: Welcome to the Wonder Software Web site

189 Background Properties

190 Background properties Define the background effects of an element Effects include color, using an image for a background, repeating an image and positioning an image

191 Background properties Basic syntax  background  background-colorbackground-color  background-imagebackground-image  background-repeatbackground-repeat  background-attachmentbackground-attachment  background-positionbackground-position

192 Background properties All attributes can be set in a single declaration: background: #000000 url(‘mark.gif’) no- repeat fixed center

193 Background properties Setting the body background (internal CSS) body { background: #000000 url(‘mark.gif’) no-repeat fixed center }

194 Background properties Setting the body background (external CSS) body: { background: #000000 url(‘mark.gif’) no-repeat fixed center }

195 Background properties Elements can also be set separately body { background-image: url(mark.gif); background-color: navy }

196 Text Properties

197 Text properties Controls the appearance of text in the web page

198 Text properties Commonly used attributes  color  direction  text-align  text-decoration  text-indent

199 Text properties color  sets the color of the text  color can be represented by the color name (red), an rgb value (rgb(255,0,0)), or by a hexadecimal number (#ff0000) Syntax  body {color: #ff0000}

200 Text properties direction  sets the direction of the text  can be set as left to right (ltr) or right to left (rtl) Syntax  body {direction: rtl}

201 Text properties text-align  aligns the text in an element  possible values are left, right, center and justify Syntax  p {text-align: center}

202 Text properties text-decoration  adds certain decoration elements to the text  possible values are none, underline, overline, line-through and blink Syntax  p {text-decoration: underline}

203 Text properties text-indent  indents the first line of text inside an element  possible values are length (defines a fixed value) and % (defines a % of the parent element) Syntax  p {text-indent: 20px}

204 Font Properties

205 Font properties Define the look of the font in text areas One of the broader sets of properties in CSS

206 Font properties font font-style font-variant font-weight font-size/line-height font-family

207 Font properties font-style normal italic oblique Syntax: body {font-style: italic}

208 Font properties font-variant normal  font displays as is small-caps  font displays in all capitals, with lower case letters in smaller size Syntax: body {font-variant: small-caps}

209 Font properties font-weight normal bold bolder lighter weighted values Syntax: body {font-weight: bold}

210 Weighted values range from 100 – 900 400 is the same as normal weight 700 is the same as bold weight

211 Font properties font-size xx-small to xx-large smaller  smaller than parent larger  larger than parent %  % of the parent Syntax: body {font-size: 20px} {font-size: x-large} {font-size: 125%}

212 Font properties font-family family-name  “times”, “arial”, “courier”, “verdana” generic-family  “serif”, “sans-serif”, “monospace” Syntax: body {font-family: verdana, sans-serif}

213 Border Properties

214 Border properties Allows you to specify the style, color and width of an element’s border Many different properties can be applied

215 Border properties You can specify the width, style, color, thickness and on which sides the border appears

216 Margin Properties

217 Margin properties Define the space around elements You can use negative values to overlap content Margins can be set independently or collectively Can be set to auto, a fixed length or a % of the total height of the document

218 Margin properties Properties  margin  margin-top  margin-right  margin-bottom  margin-left

219 Margin properties margin-bottom auto  set by the browser length  fixed % Syntax: h1 {margin-bottom: 20px}

220 Margin properties Can be set in one declarationone declaration Think clock face  top, right, bottom, left h1 {margin: 10px 20px 30px 40px}

221 Margin properties All margins can be set the same h1 {margin: 40px}

222 Margin properties Margin settings can be paired (left and right, top and bottom) h1 {margin: 40px 5%} In this example, the top and bottom margins would be 40 pixels, While the left and right margins would be 5% of the total height of the document.

223 Margin properties 0 size margins do not need to be specified. 0px, 0pt and 0 are all equivalent. h1 {margin: 40px 0 5% 0} In this example, the top margin would be 40 pixels, the left and right margins would be 0, and the bottom margin would be 5% of the total height of the document.


Download ppt "Web Programming, Building Internet Applications - Chris Bates."

Similar presentations


Ads by Google