html_css-

97
HTML and CSS by Peter Tucker Associate Professor of Math and Computer Science Whitworth University As presented February 2009 to Online J-Lab

Upload: fazal-amin

Post on 07-Sep-2015

2 views

Category:

Documents


0 download

DESCRIPTION

learn html

TRANSCRIPT

  • HTML and CSSby Peter TuckerAssociate Professor of Math and Computer ScienceWhitworth University

    As presented February 2009 to Online J-Lab

  • Markup LanguagesA markup language embeds tags within regular textText file edit with notepad

    SGML Standard Generalized Markup LanguageGeneric language conceived in the 60sLanguage to separate content and structureElements identify text objectsHTML Hypertext Markup LanguageBased on SGMLMost common markup language for Internet pagesXML Extensible Markup LanguageAlso based on SGMLVery flexibleCommonly used for information exchange

  • HTML EditorsHTML Files are simply text filesNotepad and WordPad are fine text editorsEmacs and XEmacs are good, and also work in LinuxMany freeware HTML editors existCoffeeCup is a good free version (and better commercial version)Many others: search for HTML Editor on www.download.comBe sure to check the licensing agreementsCommercial softwareMicrosoft Expression Studio is on these machinesMacromedia DreamWeaver is on these machinesVisual Studio is also on these machines

  • Server basicsHTML file is requested by userRequest travels over internet to proper machineInternet server computer locates file and respondsInternetInternetServerSoftwarefile.html...

  • Markup TagsTags are used to separate structure from contentUsually placed inside < >E.g. defines the start of an HTML pageClosed with E.g. closes an HTML pageGenerally: content content is processed/displayed according to the meaning of tagTags may be nested content more more Nesting must be "balanced"

    Tags with no content can optionally close themselvesE.g. same as

  • More On TagsTags are not case-sensitive = = Lower case is preferred

    Tags often contain attributesSpecify specific behavior for tagAttribute values contained in sE.g.

    Whitespace (space, tab, enter) ignored (except the first)This is spaced = This is spaced = This is spaced

  • HTML Skeleton Pagehtml indicates the type of markup used

    head contains header informationtitle gives page title (window title bar)

    body contains main content

  • Our First PageDefines an HTML greeting page

    Sets Title Bar text

    Display Paragraph

    White space ignored by browser

    My First Page

    Hello World! Welcome to CS301

    First page

  • In-class ExerciseOn your ownType in the given web pageSave the file, and double-click on it

    Modify the titleModify the content

    My First Page

    Hello World!

  • HTML TagsHeadings: , , , Various headings in your documentE.g. title , chapters , sections , subsections Paragraphs: Define new paragraphNew line before and afterLine break: New line, but not new paragraphHorizontal rule: Draw horizontal line across pageComment: Ignored by browser

  • Example

    Cinderella

    Cinderella or, The Little Glass Slipper Chapter 1 There lived once a gentleman who married for his second wife the proudest woman ever seen. She had two daughters of the same spirit, who were indeed like her in all things. No sooner was the wedding over than the stepmother began to show her ill-temper; she could not bear her young step-daughter's gentle ways, credit to www.childrensbooksonline.org

    Cinderella, version 1

  • Text-formatting TagsMany formatting tags in HTMLWrap text with tags: CS301 is a great Jan Term class!

    TagDescriptionDefines bold textDefines big textDefines emphasized textDefines italic textDefines small textDefines strong textDefines subscripted textDefines superscripted textDefines inserted textDefines deleted text

  • In-class ExerciseEnhance the web page you designed earlier

    Try some of the different tags listedGive six different formatted versions of Hello World!Add comments describing the difference between each versionTry nesting some of the tags

  • HTML LinksLinking to other pages is the point of the InternetAnchor: Common attributes:href destination pagetarget Where to open page (e.g. target="_blank" opens a new browser window)name Anchor on this page

    Examples:Go to our school!

    Go to start

  • Example, refined

    Cinderella Paragraph #1 Paragraph #2 Credits Back to top Back to top credit to Childrens Online Books Back to top

    Cinderella, version 2

  • In-class ExerciseTry out anchorsDesign a new web page that has links to six of your favorite web pagesSort of a bookmark page

  • TablesWe want to display tabular data

    Tags: Define a tableAttributes: border border thickness Define a table row Define table dataAttributes: colspan # of columns to cover with this data rowspan # of rows to cover with this data Define table heading

  • Example

    Cast for Cinderella

    Cast of voices for Disney's Cinderella (1950)

    CHARACTERVOICE TALENT CinderellaIlene Woods Lady TremaineEleanor Audley DrizellaRhoda Williams AnastasiaLucille Bliss

    Cinderella cast

  • In-class ExerciseDesign a web page that displays the point totals for each quarter and the whole game for three basketball gamesGet data from http://sports.espn.go.com/nba/scoreboard

  • ListsDisplay a marked list of itemsUnordered List: : list itemOrdered List: : list itemDefinition List: : Dictionary Term: Dictionary Definition

  • Example Conferences: NFC East NFC North

    Standings: NFC East (*) NY Giants (x) Philadelphia Dallas Washington xclinched playoff zclinched division *clinched homefield through playoffs NFL Standings

  • ImagesText is boringImages make a web site more interestingTag: Attributes: src, alt

    src is a URLalt is for text-only browsers, "hovering"

  • Example Conferences: NFC NFC East NFC North NFC South NFC West AFC AFC East AFC North AFC South AFC West

    Standings: (x)Seattle St.Louis Arizona SanFrancisco Enhanced NFL Standings

  • In-class ExerciseModify your basketball scoreboard pageAdd team logos on the score pages

  • Images as LinksWe've seen how to link to other pages Go to Whitworth

    We've also seen how to put images on the screen

    We can put the two together Go Bucs!

  • In-class ExerciseOpen the "bookmark" page you constructedInstead of using text for the links, where appropriate, use an image.Maybe an image is available on that site that makes sense?

  • HTML tagDefines a generic containerAllows us to set up tags as a group (e.g. menu bar, image list, )Attributesalign (left, center, right, justify)class

    For now, it isn't much helpWhen we learn CSS, styles can be applied to divIt'll come up a bit Thursday

  • Example

    Cast for Cinderella

    Cast of voices for Disney's Cinderella (1950) CHARACTERVOICE TALENT CinderellaIlene Woods

    CHARACTERVOICE TALENT CinderellaIlene Woods

    CHARACTERVOICE TALENT CinderellaIlene Woods

    Cast_div

  • HTML FormsMany Internet applications require user inputE.g. Search engine pages, customer support, BlogsHTML uses forms to set up user inputMany different form controlsTag begins a form sectionAttributes: name, action, method, id

  • Form Input ObjectsForms need objects to get information from usersUsually use tagAttributes: name, type, value, id

    Type attribute specifies the kind of input objectsubmit, text, textarea, checkbox, radio,

    We'll discuss these in more detail soon

  • Simple form search engine page

    Search the Internet

    CS301 -- Internet Search Page Search for:

    Initial Search Page

  • In-class ExerciseDesign a form Get the user's name and password in a textbox (e.g. )Include a "submit" button (e.g. )

  • Form optionsOur form doesnt (yet) do anythingWe need to direct its values to some destination siteOnce the user hits the submit button

    action, method attributes of specify thisaction: URL to destination sitemethod: how to send the data (get, post)Example: Search Page #2

  • Example

    Search the Internet

    CS301 -- Internet Search Page Powered by: Search for:

  • In-class ExerciseCreate a simple web page that says "thank you for your input"Similar to the "hello world" pageModify your form to use the "thank you" page as the action of the formTry it outWhen you press submit, then you should see your thank you page

  • Form MethodsThe method attribute accepts two values, get and postget Submitted URL contains name/value pairs for each control on web pageUsers bookmarks contain query answersUsers see URL security issues?postSubmitted URL does not contain control valuesUser bookmarks do not keep query resultsUsers do not see URLGet Search Page #2Post Search Page #2

  • Form ControlsForms must have more than text boxes and buttonsWe want check boxes, radio buttons, password fields, multi-line fields,

    HTML provides all of these with the tagUsing the type attribute to choose the controlUse the name attribute to name it (for later)

  • Text BoxesText field:
  • Example

    PHP Self Description

    Name: Password: Description:

  • ButtonsSubmit:
  • Example

    Search for:

    Choose a search engine: Google Yahoo A9 Checkbox that does nothing (sorry)

  • In-class ExerciseDesign a form that uses radio buttons to list your classes for spring semesterHave the user choose the course they're about to attend, then hit submit

  • List BoxesDrop-down list: Give user list of optionsAttribute name defines control name

    to define each optionAttributes: value, selectedNew Search Page

  • Example

    Search for: Choose a search engine: Google Yahoo A9 Checkbox that does nothing (sorry)

  • In-class ExerciseDesign a form that lists ice cream flavorsAsk the user to choose their favorite ice cream

  • Page and Form LayoutCommon use for HTML tables is for page layoutGenerally, programmers have no layout control over their pagesE.g. 2-column newspaperWell see later that is also very useful, especially with CSS

    border="0" (why?)td supports width, bgcolor, colspan attributes

  • Making Forms More ReadableExample: Form for a restaurant surveyNeed to rate things on scale of 1-5ServiceFood qualityPriceLayout

  • Example

    Restaurant Survey

    Thank you! Please fill out this survey Lowest Highest 12 345 Service

  • Now we need the DIV and SPAN tagsRecall marks areas with a name is similar, but works within a tag

    Classroom Research conducted by Students in the Math and Computer Science Department at Whitworth University

    We will see that, by marking groups, we can easily make display changesFall 2008 -- CS374: Database Management SystemsEdited by Peter A. TuckerAustin Abelar, Parallel Query Processing Using Various Techniques of Multicore Technology

  • What is CSSCSS Cascading Style SheetsProblem: HTML developers have little control of how things lookModifying a pages format through HTML can be very messySolution: Cascading style sheetstell the browser how to display objects

    Style sheets can be embedded in the HTML file or saved externallyWe will focus on CSS1More widely accepted than CSS2

  • Motivation CS Student Research PagePage with a number of papers listed, by class

    Three versionsFirst, littered with table data tags to place itemsSecond and third, same HTML, different style sheets

  • Next Motivation CSS Zen GardenZen Garden is a great illustration of the power of CSSwww.csszengarden.com

    Let's take a look

  • CSS SyntaxValues in a style sheet have the following syntax: selector {property: value}

    Where:selector: the HTML tag to specifyproperty: the property of tag to setvalue: the new value for that tags propertySemi-colon delimited list (tag {p1: v1; p2: v2; })

  • Examplesp {color: green}Make contents of green typeface

    p { text-align: center; color: green }Multiple property settings ( centered, green)

    h1,h2,h3,h4,h5,h6,p { text-align: center; color: green }Grouping of multiple tags

  • Applying CSSEmbedded in HTML page (Internal)Linked into HTML page (External)

    Simple CSS Test h1,h2,h3,h4,h5,h6,p {text-align: center; color: green}

    Simple CSS Test

    InternalExternalh1,h2,h3,h4,h5,h6,p {text-align: center; color: green}

  • In-class ExerciseConstruct a style sheet internally to one of your existing web pagesChoose tags, and some colorReload it in a browser

    Construct an external style sheetWrite it using any text editor (notepad, Expression Web, VS.NET, )Link it into another one of your existing web pagesHang onto these files for later work

  • CSS ClassesWe may not want a single style for all instances of a tagE.g. is very commonClasses specify different kinds of styles for a tagSyntax: selector.class {prop: val}

    Usage:

    Both selector and class are optionalMissing selector: applies to all tags with class=cMissing class: applies to all instances of a tagp.right {text-align: right} p.center {text-align: center} Right-aligned Centered

  • Example

    Simple CSS Test .global {color: darkred} p {color: green} p.center {text-align: center} p.right {text-align: right} p.left {text-align: left}

    Heading for this page Cool Main Title in the Center Interesting text on the left other stuff on the right is this blue?

    Classes

  • Inline StylesWe can also embed styles into a single tagWe lose many advantages of style sheetsLimited useSyntax: Example:

    This is a paragraph

  • Which style to choosePossible conflict of stylesexternal vs. internal vs. inline

    Order:Browser default External Style Sheet Internal Style Sheet (inside the tag) Inline Style (inside HTML element)

  • OK, Now We Need SpecificsWe know how to use CSSReal Power one CSS file controls pages on entire siteEasy to update entire lookWhat are the possibilities?What properties can be set for various tags?

  • Background

    PropertyDescriptionValuesbackground-attachmentDoes background image scroll?scrollfixedbackground-colorBackground colorcolor-rgbcolor-#color-nametransparentbackground-imageURL to imageurlbackground-positionPosition of background imagetop righttop leftbackground-repeatIs image repeated? How?repeatrepeat-x

  • Example

    Simple CSS Test p.bcolor {background-color: lightgrey} p.bgimage { background-image: url('main_logo.gif'); background-position: center; background-repeat: no-repeat; }

    CSS TEST This is a simple test of style sheets This is another simple test of style sheets

    Backgrounds

  • Another Example

    Simple CSS Test p.lgrey {background-color: lightgrey} p.orange { text-align: center; color: orange; font-weight: bolder; } body { background-image: url('http://www.whitworth.edu//Logo.gif'); background-position: center; background-repeat: no-repeat; }

    CSS TEST This is a simple test of style sheets This is another simple test of style sheets

    Background2

  • In-class ExerciseExperiment with the background settingsUse different browsers

    PropertyDescriptionValuesbackground-attachmentDoes background image scroll?scrollfixedbackground-colorBackground colorcolor-rgbcolor-#color-nametransparentbackground-imageURL to imageurlbackground-positionPosition of background imagetop righttop leftbackground-repeatIs image repeated? How?repeatrepeat-x

  • Text

    PropertyDescriptionValuescolorText colorcolor-rgbcolor-#color-nameletter-spacingSpacing between lettersnormalLengthtext-alignAligns text in elementleftrightcenterjustifiedword-spacingSpacing between wordsnormallength

  • Example

    Simple CSS Test p.squish {letter-spacing: -5px} p.expand {letter-spacing: 25px} p.wrdspace { word-spacing: 20px}

    CSS TEST This is a simple test This is a simple test This is another simple test

    Texts

  • In-class ExerciseExperiment with the text settings

    PropertyDescriptionValuescolorText colorcolor-rgbcolor-#color-nameletter-spacingSpacing between lettersnormalLengthtext-alignAligns text in elementleftrightcenterjustifiedword-spacingSpacing between wordsnormallength

  • Font

    PropertyDescriptionValuesfont-familyPrioritized, comma-separated list of font namesfamily-namegeneric-namefont-sizeSize of fontxx-smallxx-largefont-styleStyle of fontnormalitalicobliquefont-variantSmall-caps?normalsmall-capsfont-weightWeight of a fontnormalboldbolderlighter

  • Example

    Simple CSS Test body {font-family:"Bookman Old Style", Arial, Helvetica, sans-serif} p.ariel {font-family: sans-serif} p.code {font-family: courier}

    CSS TEST This is a simple test of style sheets This is a simple test of style sheets This is another simple test of style sheets

    Fonts

  • In-class ExerciseExperiment with the font settings

    PropertyDescriptionValuesfont-familyPrioritized, comma-separated list of font namesfamily-namegeneric-namefont-sizeSize of fontxx-smallxx-largefont-styleStyle of fontnormalitalicobliquefont-variantSmall-caps?normalsmall-capsfont-weightWeight of a fontnormal boldbolder lighter

  • Border

    PropertyDescriptionValuesborder-colorColor for bordercolorborder-styleStyle for bordernone, hidden, dotted, dashed, solid, double, groove, ridge, inset, outsetborder-widthWidth of all four bordersthinmediumthickborder-XXXX-YYYYSpecific border settingsXXXX={left, right, top, bottom}YYYY={color, style, width}

  • Example

    Simple CSS Test th { border-width: thick; border-style: ridge; } td { border-style: dashed; border-color: darkslategray; } p { border-bottom-style: outset; background-color: lightyellow; color: darkslategray;}

    CS301 - Internet Application Development Title Author Track Foundation Flash CS3 for Designers T. Green, D. Stiller Flash ASP.NET 3.5 Unleashed S. Walther ASP.NET

    Borders

  • In-class ExerciseExperiment with borders

    PropertyDescriptionValuesborder-colorColor for bordercolorborder-styleStyle for bordernone, hidden, dotted, dashed, solid, double, groove, ridge, inset, outsetborder-widthWidth of all four bordersthinmediumthickborder-XXXX-YYYYSpecific border settingsXXXX={left, right, top, bottom}YYYY={color, style, width}

  • Lists

    PropertyDescriptionValueslist-style-imageImage for items in a listnoneurllist-style-positionWhere marker should be locatedinsideoutsidelist-style-typeType of markernone, disc, circle, square, decimal, decimal-leading-zero, lower-roman, upper-roman, lower-alpha, upper-alpha, lower-greek, lower-latin, upper-latin, hebrew, armenian, georgian, cjk-ideographic, hiragana, katakana

  • Example

    NFL Standings ul {list-style-type: hebrew } ul.nfc {list-style-image: url('NFC.gif')} ul.afc {list-style-image: url('AFC.gif')}

    NFL Standings as of 21 December 2006 Conferences: NFC NFC East NFC North NFC South NFC West AFC AFC East AFC North AFC South AFC West Lists

  • In-class ExerciseExperiment with lists

    PropertyDescriptionValueslist-style-imageImage for items in a listnoneurllist-style-positionWhere marker should be locatedinsideoutsidelist-style-typeType of markernone, disc, circle, square, decimal, decimal-leading-zero, lower-roman, upper-roman, lower-alpha, upper-alpha, lower-greek, lower-latin, upper-latin, hebrew, armenian, georgian, cjk-ideographic, hiragana, katakana

  • Dimension

    PropertyDescriptionValuesheightHeight of an imageautolength%widthWidth of an imageautolength%line-heightHeight of linesnormalnumberlength%

  • Example

    Simple CSS Test

    Go Bucs!

    Dimensions

  • Pseudo-classesSome selectors can have special effectsAnchor () is one such selectorIt supports link, visited, hover and activeNote: a:hover MUST come after a:linkNote: a:active MUST come after a:hoverWe may want different behaviors for each caseSyntax:selector:pseudo-class {property: value}selector.class:pseudo-class {property: value}

  • Example 1

    a:link {color: #FF0000}a:visited {color: #00FF00}a:hover {color: #FF00FF}a:active {color: #0000FF}

    This is a link

    Note: a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective!!

    Note: a:active MUST come after a:hover in the CSS definition in order to be effective!!

    Slightly modified from W3Schools.comanchor1

  • Example 2

    a.one:link {color: #ff0000} a.one:visited {color: #0000ff} a.one:hover {color: #ffcc00}

    a.two:link {color: #ff0000} a.two:visited {color: #0000ff} a.two:hover {font-size: 150%}

    a.three:link {color: #ff0000} a.three:visited {color: #0000ff} a.three:hover {background: #66ff66}

    a.four:link {color: #ff0000} a.four:visited {color: #0000ff} a.four:hover {font-family: monospace}

    Mouse over the links to see them change layout.

    changes colorchanges font-sizechanges background-colorchanges font-family

    anchor2Slightly modified from W3Schools.com

  • Final word on div tagThe tag allows positioning of a group of HTML elements.classes { position:fixed; width:170px; top:250px; font-style:oblique;}

    .papers { text-align:left; position:relative; left:190px;}

    top CS374: Fall 2008 CS499: Spring 2008 CS374: Fall 2007 CS374: Fall 2006 MA430W: Spring 2006 CS499: Spring 2006 CS374: Fall 2005

    Student Research

  • Final word on span tagThe tag also allows you to apply classes within a tagNo effect on style of text ( includes ).journaltitle {font-size:large;font-weight:bold;color:black;font-variant:small-caps;}

    .editor {font-size:small;font-style:italic;font-variant:small-caps;color:black;}

    Fall 2008 -- CS374: Database Management Systems

    Edited by Peter A. Tucker

    Student Research

  • We want to control what happens with form dataCurrently our form just sends results to Google

    It's more fun if we can control how the data is processedWe sure don't want login information to go to GoogleWe would really like to store customer information in our own databaseFor example, what if users could select their search engine?

    We need a way to respond to form inputsMust happen on the serverMany server-side options: Perl, PHP, Python, ASP.NET

    Well take a quick tour of PHP to handle our form results

  • Server basicsHTML file is requested by userRequest travels over internetInternet server locates file and respondsInternetInternetServerSoftwarefile.html

    Hello World!

  • A Brief Word on PHPPHP is a C-like language that runs on the internet server (CS1 for us)PHP scripts are embedded in HTML codeFile extension .phpInside tagA scripts output is pasted into the HTMLInternetInternetServerSoftwarePHPInterpmyfile.php

    Hello World!

  • Simple PHP script

    Simple PHP

    Simple PHP Hello worldPHP Interpreter

    IIS

    myfile.php

  • Main Motivation Processing Form DataWe really want that data that users gave usDont just send it to Google!

    The input names will be usefulWe can use $_REQUEST to read that data

  • Handling Input Example

    Simple PHP

    Name PHP

  • Scripting on the ClientWe would like an interactive web pageFor example, input validationHTML is staticNothing changesServer-side scripting gave some interactivityBut required trips to the server and back

    Client-side scripting languages give us more flexibilityProcessed by browser no trips to the server and backMany languages (VBScript, JavaScript, DHTML)Well focus on JavaScript

  • JavaScript BasicsJavaScript is a simple programming languageIt is not JavaJavaScript is embedded in HTMLMost browsers support JavaScriptThough not all!

  • What can we do in JavaScript?JavaScript is a programming language for HTML developersLike us

    JavaScript can dynamically put text into an HTML pagereact to eventsread and write HTML elementsbe used to validate data

  • Embedding JavaScriptJavaScript is embedded anywhere in HTML using the tagFor now, we will only put code in the sectionWell see other options laterFor example, the following outputs Hello World! on a web page:

    document.write("Hello World!");

    hello.html

  • Input ValidationOK, now for the most common use for JavaScript

    A form has a number of fieldsSome are required, others are notIf we send all the data to the server, then validate, we waste timeIf there is invalid input, then we should try to catch it before going to the server

    JavaScript can do this for us

  • JavaScript Input ValidationRequirementsJavaScript function that:returns true if all inputs are validreturns false if any input is invalidForm has a name associated with itForm uses the JavaScript function for its onSubmit event Input control values can be accessed in JavaScript: document.myform.myinput.valueEmail

  • Example Personal Information function validate_email() { if (document.email_addr.email.value == ""){ alert("Email must be filled out!") document.email_addr.email.focus() return false } else { return true } }

    Email: