HTML and Css Assignment (1)
HTML and Css Assignment (1)
First Program:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
Content of the document......
</body>
</html>
HTML History
Year Version
1989 Tim Berners-Lee invented www
1991 Tim Berners-Lee invented HTML
1993 Dave Raggett drafted HTML+
1995 HTML Working Group defined HTML 2.0
1997 W3C Recommendation: HTML 3.2##
1999 W3C Recommendation: HTML 4.01##
2000 W3C Recommendation: XHTML 1.0
2008 WHATWG HTML5 First Public Draft**
2012 WHATWG HTML5 Living Standard**
2014 W3C Recommendation: HTML5
2016 W3C Candidate Recommendation: HTML 5.1
Output:
Output after removing - display: block and set the padding: 25px
Semantic/Structural Elements
Tag Description
<article> Defines an article in a document
<aside> Defines content aside from the page content
<bdi> Isolates a part of text that might be formatted in a different
direction from other text outside it
<details> Defines additional details that the user can view or hide
<dialog> Defines a dialog box or window
<figcaption> Defines a caption for a <figure> element
<figure> Defines self-contained content
<footer> Defines a footer for a document or section
<header> Defines a header for a document or section
<main> Defines the main content of a document
<mark> Defines marked/highlighted text
<menuitem> Defines a command/menu item that the user can invoke from a
popup menu
<meter> Defines a scalar measurement within a known range (a gauge)
<nav> Defines navigation links
<progress> Represents the progress of a task
<rp> Defines what to show in browsers that do not support ruby
annotations
<rt> Defines an explanation/pronunciation of characters (for East
Asian typography)
<ruby> Defines a ruby annotation (for East Asian typography)
<section> Defines a section in a document
<summary> Defines a visible heading for a <details> element
<time> Defines a date/time
<wbr> Defines a possible line-break
Form Elements
Tag Description
<datalist> Specifies a list of pre-defined options for input controls
<output> Defines the result of a calculation
Input Types
HTML5 offers new semantic elements to define different parts of a web page:
• <article>
• <aside>
• <details>
• <figcaption>
• <figure>
• <footer>
• <header>
• <main>
• <mark>
• <nav>
• <section>
• <summary>
• <time>
<section> Element
A home page could normally be split into sections for introduction, content, and
contact information.
Example 2
<!DOCTYPE html>
<html>
<body>
<section>
<h1>Sathyabama Institute of Science and Technology</h1>
<p>Sathyabama Institute of Science and Technology (A Christian Minority Institution)
formerly known as Sathyabama Engineering College was established in 1987 by Dr.
Jeppiaar. It is a premier institute imparting knowledge in the areas of engineering, science,
technology and education. The institution's progress and contribution to the field of technical
education for over two decades resulted in granting Deemed University status on 16th July,
2001. The University has been awarded as Category "A" University by Ministry of Human
Resources Development (MHRD), Government of India and accredited by NAAC with Grade
"A" in the year 2017, certified with DNV-GL ISO 9001 standard and offering exemplary
education from last 30 years.</p>
</section>
<section>
<h1>Department of Computer Science and Engineering</h1>
<p>The department of Computer Science and Engineering (CSE) is one among the leading
and oldest departments of Sathyabama. The department is reputed for its excellence in
teaching and training engineering students for generations since 1987. The Department
caters Under Graduate, Post Graduate and Ph.D. courses in all the specialized areas of
computing. The Department has pioneered in setting education standards par excellence
that can be sensed by the presence of alumni in all the leading Multinational software firms
like Microsoft, Infosys, Oracle, Verizon, Virtusa, Cognizant, Wipro etc.</p>
</section>
</body>
</html>
<header> Element
The <header> element specifies a header for a document or section.
The <header> element should be used as a container for introductory content.
Can have several <header> elements in one document.
<!DOCTYPE html>
<html>
<body>
<article>
<header>
<h1>Header</h1>
<p>Paragraph</p>
</header>
<p>Some Text Goes Here</p>
</article>
</body>
</html>
<footer> Element
The <footer> element specifies the footer for a document or section.
A <footer> element should contain information about its containing element.
A footer typically contains the author of the document, copyright information, links to terms of
use, contact information, etc.
Can have several <footer> elements in one document.
<!DOCTYPE html>
<html>
<body>
<footer style="color: green;">Copyright © (2018) SIST(DU), Chennai.</footer>
</body>
</html>
<nav> Element
The <nav> element defines a set of navigation links.
<!DOCTYPE html>
<html>
<body>
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
</body>
</html>
Output:
HTML | CSS | JavaScript | jQuery
<aside> Element
<!DOCTYPE html>
<html>
<body>
<p>Department of Computer Science and Engineering</p>
<aside>
<h4>Elective Subjects</h4>
<p>Internet of Things</p>
<p>Python Programming</p>
<p>User Interface Technologies</p>
</aside>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Browsers Logo</p>
<figure>
<img src="chrome.jpg" alt="chrome" width="304" height="228">
<figcaption>Fig.1 - Google Chrome</figcaption>
</figure>
<figure>
<img src="firefox.jpg" alt="firefox" width="304" height="228">
<figcaption>Fig.2 - Mozilla Firefox</figcaption>
</figure>
<figure>
<img src="safari.jpg" alt="safari" width="304" height="228">
<figcaption>Fig.3 - Apple Safari</figcaption>
</figure>
<figure>
<img src="opera.jpg" alt="Opera" width="304" height="228">
<figcaption>Fig.4 - Opera</figcaption>
</figure>
<figure>
<img src="ie.jpg" alt="ie" width="304" height="228">
<figcaption>Fig.5 - Microsoft Internet Explorer</figcaption>
</figure>
</body>
</html>
Input Types
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php">
User name:<br><input type="text" name="userid"><br>
User password:<br><input type="password" name="psw">
<input type="submit" value="Login">
<input type=”reset”>
</form>
<p>The characters in a password field are masked (shown as asterisks or circles).</p>
</body>
</html>
c. Button
<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
<input type="button" onclick="alert('Hello World!')" value="Click Me!">
</body>
</html>
d. Color, date, datetime-local, email, month, numeric, range, tel, time, url
<!DOCTYPE html>
<html>
<body>
<p>Depending on browser support:<br></p>
<form action="/action_page.php">
<p>A color picker can pop-up when you enter the input field. Used in input fields that
should contain a color.</p>
Select your favorite color: <input type="color" name="favcolor" value="#0000ff">
<p>A date picker can pop-up when you enter the input field. Is used for input fields
that should contain a date.</p>
Birthday: <input type="date" name="bday">
<p>DatePicker with Restrictions</p>
Enter a date before 01-01-1980:
<input type="date" name="bday" max="1979-12-31"><br>
Enter a date after 01-01-2000:
<input type="date" name="bday" min="2000-01-02"><br>
<p>Specifies a date and time input field, with no time zone.</p>
Birthday (date and time): <input type="datetime-local" name="bdaytime">
<p>Selects Month & Year</p>
Birthday (month and year): <input type="month" name="bdaymonth">
<p>Allows the user to select a week and year.</p>
Select a week: <input type="week" name="year_week">
<p>email: Used for input fields that should contain an e-mail address. Depending on
browser support, the e-mail address can be automatically validated when submitted. Some
smart phones recognize the email type, and adds ".com" to the keyboard to match email
input.</p>
E-mail: <input type="email" name="email">
<p>Defines a numeric input field. Set restrictions on what numbers are accepted.</p>
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
<p>The input type "range" can be displayed as a slider control. Set restrictions on
what numbers are accepted with the min, max, and step attributes. Default 0 to 100</p>
Points:
<input type="range" name="points" min="0" max="10">
<p>Tel is used for input fields that should contain a telephone number.</p>
Telephone: <input type="tel" name="usrtel">
<p>Time allows the user to select a time (no time zone).</p>
Select a time: <input type="time" name="usr_time">
<p>URL: is used for input fields that should contain a URL address. Depending on
browser support, the url field can be automatically validated when submitted. Some smart
phones recognize the url type, and adds ".com" to the keyboard to match url input.</p>
Add your homepage: <input type="url" name="homepage">
</br></br>
Browsers List: <input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</input>
<p>Try selecting more than one file when browsing for files.</p>
Select Files: <input type="file" name="fileChooser" multiple>
</br></br><input type="submit"/>
</form>
<p><b>Note:</b>
<ul><li><strong>type="color"</strong> is not supported in Internet Explorer 11 and earlier
versions or Safari 9.1 and earlier versions.</li>
<li><strong>type="date"</strong> is not supported in Internet Explorer 11 and earlier
versions.</li>
<li><strong>type="datetime-local"</strong> is not supported in Firefox, or Internet Explorer
12 and earlier versions.</li>
<li><strong>type="month"</strong> is not supported in Firefox, or Internet Explorer 11 and
earlier versions.</li>
<li><strong>type="week"</strong> is not supported in Firefox, or Internet Explorer 11 and
earlier versions.</li>
<li><strong>type="email"</strong> is not supported in IE9 and earlier.</li>
<li><strong>type="numeric"</strong> is not supported in IE9 and earlier.</li>
<li><strong>type="range"</strong> is not supported in IE9 and earlier.</li>
<li><strong>type="tel"</strong> is only supported in Safari 8 and newer versions.</li>
<li><strong>type="time"</strong> is not supported in IE12 and earlier.</li>
<li><strong>type="url"</strong> is not supported in IE9 and earlier.</li>
<li>The <strong>datalist</strong> tag is not supported in Internet Explorer 9 and earlier
versions, or in Safari</li>
<li><strong>type="file"</strong> The multiple attribute of the input tag is not supported in
Internet Explorer 9 and earlier versions</li>
</ul></p>
</body>
</html>
Input Restrictions
Attribute Description
disabled Specifies that an input field should be disabled
max** Specifies the maximum value for an input field
maxlength Specifies the maximum number of character for an input field
min** Specifies the minimum value for an input field
pattern** Specifies a regular expression to check the input value against
readonly Specifies that an input field is read only (cannot be changed)
required** Specifies that an input field is required (must be filled out)
size Specifies the width (in characters) of an input field
step** Specifies the legal number intervals for an input field
Value Specifies the default value for an input field
** - Supported only in HTML5
Input Attributes
• autocomplete • formtarget • required
• autofocus • height and width • step
• form • list • value
• formaction • min • readonly
• formenctype • multiple • disabled
• formmethod • pattern (regexp) • maxlength
• formnovalidate • placeholder • size
• max
Form Attributes
• autocomplete whether a form or input field should have autocomplete on or off.
• novalidate form data should not be validated when submitted.
Example
<!DOCTYPE html>
<html>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40"
stroke="green" stroke-width="4" fill="yellow" />
</svg>
<svg width="400" height="100">
<rect width="400" height="100"
style="fill:rgb(0,0,255);stroke-width:10;stroke:rgb(0,0,0)" />
</svg>
<svg width="400" height="180">
<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:15;opacity:0.5" />
</svg>
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />
</svg>
<svg height="130" width="500">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana" x="50" y="86">CSE</text>
Sorry, your browser does not support inline SVG.
</svg>
</body>
</html>
Canvas
• Used to draw graphics on a Web page.
• The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
• The <canvas> element is only a container for graphics. Use JavaScript to actually
draw the graphics.
• Canvas has several methods for drawing paths, boxes, circles, text, and adding
images.
A canvas is a rectangular area on an HTML page. By default, a canvas has no border
and no content.
• The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>
Example
<!DOCTYPE html>
<html>
<body>
<canvas id="lineCanvas" width="200" height="100" style="border:1px solid
#000000;"></canvas>
<canvas id="circleCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<canvas id="textCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<canvas id="lgradientCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<canvas id="cgradientCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
<canvas id="imageCanvas1" width="450" height="400" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p>Image to use:</p>
<img id="sistlogo" src="sist_logo1.jpg" alt="SIST Logo" width="450" height="400">
<p>Canvas to fill:</p>
<canvas id="imageCanvas2" width="450" height="400"
style="border:1px solid #d3d3d3;"></canvas>
<p><button onclick="loadImageCanvas()">Load Image into Canvas</button></p>
<script>
var c = document.getElementById("lineCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
var c = document.getElementById("circleCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
var c = document.getElementById("textCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("SIST",10,35);
ctx.strokeText("CSE",10,75);
var c = document.getElementById("lgradientCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
var c = document.getElementById("cgradientCanvas");
var ctx = c.getContext("2d");
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
var c = document.getElementById("imageCanvas1");
var ctx = c.getContext("2d");
var img1=new Image();
img1.onload = function() {
ctx.drawImage(img1, 0, 0);
};
img1.src="sist_logo1.jpg";
function loadImageCanvas() {
var c = document.getElementById("imageCanvas2");
var ctx = c.getContext("2d");
var img = document.getElementById("sistlogo");
ctx.drawImage(img,10,10);
}
</script>
</body>
</html>
Difference between SVG and Canvas
SVG Canvas
Language for describing 2D graphics in XML. Draws 2D graphics, on the fly
Save the resulting image as .png or .jpg
Resolution dependent Resolution independent
No support for event handlers Support for event handlers
Poor text rendering capabilities Best suited for applications with large
rendering areas (Google Maps)
Slow rendering if complex
Well suited for graphic-intensive games Not suited for game applications
Google Maps
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="map" style="width:400px;height:400px">
<script>
function myMap() {
// Set Map Properties
var mapOptions = {
// Where to center the Map using the latitude and longitude
center: new google.maps.LatLng(12.87, 80.21),
// Zoom to the location
zoom: 15,
// ROADMAP, SATELLITE, HYBRID, TERRAIN
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
</script>
<!-- To get a new API key for Google Map use the link:
https://developers.google.com/maps/documentation/javascript/get-api-key
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDjfMhzcBFlvsD15GR_Ongye4Rp
_xFDYlY&callback=myMap"></script>
</body>
</html>
HTML Multimedia
• Multimedia on the web is sound, music, videos, movies, and animations.
• Web pages often contain multimedia elements of different types and formats.
• Examples: Images, music, sound, videos, records, films, animations, and more.
• Multimedia elements (like audio or video) are stored in media files.
• The most common way to discover the type of a file, is to look at the file extension.
• Multimedia files have formats and different extensions like: .swf, .wav, .mp3, .mp4,
.mpg, .wmv, and .avi.
Video Formats
Audio Formats
<!DOCTYPE html>
<html>
<body>
<video width="320" height="240" controls autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
</body>
</html>
• The controls attribute adds video controls, like play, pause, and volume.
• If height and width are not set, the page might flicker while the video loads.
• The <source> element allows to specify an alternative video files which the browser
may choose from. The browser will use the first recognized format.
• The text between the <video> and </video> tags will only be displayed in browsers
that do not support the <video> element.
• To start a video automatically use the autoplay attribute.
Audio
To play an audio file in HTML, use the <audio> element
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="audio.ogg" type="audio/ogg">
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
Plugins
• The <object> element is supported by all browsers.
• The <object> element defines an embedded object within an HTML document.
• It is used to embed plug-ins (like Java applets, PDF readers, Flash Players) in Web
pages.
• The <embed> element is supported in all major browsers.
• The <embed> element also defines an embedded object within an HTML document.
• Web browsers have supported the <embed> element for a long time. However, it has
not been a part of the HTML specification before HTML5.
<!DOCTYPE html>
<html>
<body>
Flash File:
<object width="400" height="50" data="bookmark.swf"></object>
<embed width="400" height="50" src="bookmark.swf">
HTML Page:
<object width="100%" height="500px" data="snippet.html"></object>
<embed width="100%" height="500px" src="snippet.html">
Load Image :
<object data="sist_logo.jpg"></object>
<embed src=" sist_logo.jpg ">
</body>
</html>
Youtube
Autoplay
Value 0 (default): The video will not play automatically when the player loads.
Value 1: The video will play automatically when the player loads.
PlayList
A comma separated list of videos to play (in addition to the original URL).
Loop
Value 0 (default): The video will play only once.
Value 1: The video will loop (forever).
Controls
Value 0: Player controls does not display.
Value 1 (default): Player controls display.
GeoLocation API
• The HTML Geolocation API is used to get the geographical position of a user.
• Since this can compromise privacy, the position is not available unless the user
approves it.
• Geolocation is most accurate for devices with GPS
Example
• Check if Geolocation is supported
• If supported, run the getCurrentPosition() method. If not, display a message to the
user
• If the getCurrentPosition() method is successful, it returns a coordinates object to the
function specified in the parameter (showPosition)
• showPosition() function outputs the Latitude and Longitude
• showError() function outputs the error (if any)
• options – set accuracy, timeout, refresh status can be set
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="pos1"></p>
<p id="pos2"></p>
<div id="mapholder"></div>
<script>
var x = document.getElementById("pos1");
var x1 = document.getElementById("pos2");
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, options);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
/* API Key - https://developers.google.com/maps/documentation/static-maps/ */
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&key=AIzaSyDR4GC3N3pmR6nOVMuDMsqYDgb1V9BL
de0";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
x1.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x1.innerHTML = "Geolocation is not supported by this browser.";
}
}
</script>
</body>
</html>
Other Functions
• watchPosition() - Returns the current position of the user and continues to return
updated position as the user moves (like the GPS in a car).
• clearWatch() - Stops the watchPosition() method.
• Requires an accurate GPS device to test this.
Mark Map
<script
src="https://maps.google.com/maps/api/js?key=AIzaSyCP3McXvXtA0kPEGM6OOjstZvOWh
cbIJ5s"></script>
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latlon = new google.maps.LatLng(lat, lon);
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
var mapholder = document.getElementById('mapholder');
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
var marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
Example:
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
width: 400px;
height: 400px;
float: left;
padding: 10px;
border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("logo", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("logo");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<p>Drag the SIST LOGO into the rectangle:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<img id="drag1" src="sist_logo1.jpg" draggable="true" ondragstart="drag(event)" width="400"
height="400">
</body>
</html>
• To make an element draggable, set the draggable attribute to true:
• <img draggable="true">
• The ondragstart attribute calls a function, drag(event), that specifies what data to be
dragged.
• The dataTransfer.setData() method sets the data type and the value of the dragged
data
• The ondragover event specifies where the dragged data can be dropped.
• By default, data/elements cannot be dropped in other elements. To allow a drop, have
to prevent the default handling of the element.
• This is done by calling the event.preventDefault() method for the ondragover event.
Web Storage
• With web storage, web applications can store data locally within the user's browser.
• Before HTML5, application data had to be stored in cookies, included in every server
request. Web storage is more secure, and large amounts of data can be stored locally,
without affecting website performance.
• Unlike cookies, the storage limit is far larger (at least 5MB) and information is never
transferred to the server.
• Web storage is per origin (per domain and protocol). All pages, from one origin, can
store and access the same data.
• HTML web storage provides two objects for storing data on the client:
o window.localStorage - stores data with no expiration date
o window.sessionStorage - stores data for one session (data is lost when the
browser tab is closed)
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
Local Storage
Example:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("deptname", "CSE");
/*
//Other method:
// Store
localStorage. deptname = "CSE";
// Retrieve
document.getElementById("result").innerHTML = localStorage. deptname;
*/
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("deptname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support
Web Storage...";
}
</script>
</body>
</html>
SessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data
for only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current
session:
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if(typeof(Storage) !== "undefined") {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support
web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>
Cascading Style Sheets (CSS)
• CSS stands for Cascading Style Sheets
• CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
• CSS saves a lot of work. It can control the layout of multiple web pages all at once
• External stylesheets are stored in CSS files
• CSS is used to define styles for your web pages, including the design, layout
and variations in display for different devices and screen sizes.
• HTML was NEVER intended to contain tags for formatting a web page!
• HTML was created to describe the content of a web page, like:
o <h1>This is a heading</h1>
o <p>This is a paragraph.</p>
• When tags like <font>, and color attributes were added to the HTML 3.2 specification,
it started a nightmare for web developers. Development of large websites, where fonts
and color information were added to every single page, became a long and expensive
process.
• To solve this problem, the World Wide Web Consortium (W3C) created CSS.
• CSS removed the style formatting from the HTML page!
• The style definitions are normally saved in external .css files. With an external
stylesheet file, you can change the look of an entire website by changing just one file!
Syntax
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red;
text-align: center;
}
</style>
</head>
<body>
<p>Welcome to SIST-DU</p>
<p>Department of Computer Science and Engineering.</p>
</body>
</html>
CSS selectors are used to "find" (or select) HTML elements based on their element name,
id, class, attribute, and more
Element Selector
The element selector selects elements based on the element name.
Can select all <p> elements on a page like this (in this case, all <p> elements will be center-
aligned, with a red text color – refer previous example)
id Selector
• The id selector uses the id attribute of an HTML element to select a specific element.
• The id of an element should be unique within a page, so the id selector is used to
select one unique element!
• To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
• The style rule below will be applied to the HTML element with id="para1":
• An id name cannot start with a number
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: blue;
}
</style>
</head>
<body>
<p id="para1">SIST-DU</p>
<p>DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING</p>
</body>
</html>
Class Selector
The class selector selects elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the name of
the class.
In the example below, all HTML elements with class="center" will be red and center-aligned:
You can also specify that only specific HTML elements should be affected by a class.
For example, only <p> elements with class="center" will be center-aligned can be set.
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
p.large {
font-size: 300%;
}
</style>
</head>
<body>
<h1 class="center">This heading will not be affected</h1>
<p class="center">This paragraph will be red and center-aligned.</p>
<p class="center large">This paragraph will be red, center-aligned, and in a large font-
size.</p>
</body>
</html>
p{
color: red;
/* This is a single-line comment */
text-align: center;
}
/* This is
a multi-line
comment */
When a browser reads a style sheet, it will format the HTML document according to the
information in the style sheet.
There are three ways of inserting a style sheet:
• External style sheet
• Internal style sheet
• Inline style
Example
mystyle.css
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Internal Style Sheet
An internal style sheet may be used if one single page has a unique style.
Internal styles are defined within the <style> element, inside the <head> section of an HTML
page
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inline Style
• An inline style may be used to apply a unique style for a single element.
• To use inline styles, add the style attribute to the relevant element.
• The style attribute can contain any CSS property.
• An inline style loses many of the advantages of a style sheet (by mixing content with
presentation)
Example
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;margin-left:30px;">Heading Element with CSS Style Applied.</h1>
<p>Paragraph Element without any style.</p>
</body>
</html>.
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style
sheet by the following rules, where number one has the highest priority:
1. Inline style (inside an HTML element)
2. External and internal style sheets (in the head section)
3. Browser default
So, an inline style (inside a specific HTML element) has the highest priority, which means
that it will override a style defined inside the <head> tag, or in an external style sheet, or a
browser default value.
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
body {background-color: linen;}
</style>
</head>
<body style="background-color: lightcyan">
</body>
</html>
Background Colours:
<h1 style="background-color:Tomato;">Tomato</h1>
<h1 style="background-color:Orange;">Orange</h1>
<h1 style="background-color:DodgerBlue;">DodgerBlue</h1>
<h1 style="background-color:MediumSeaGreen;">MediumSeaGreen</h1>
<h1 style="background-color:Gray;">Gray</h1>
<h1 style="background-color:SlateBlue;">SlateBlue</h1>
<h1 style="background-color:Violet;">Violet</h1>
<h1 style="background-color:LightGray;">LightGray</h1>
Text Colours:
<h3 style="color:Tomato;">SATHYABAMA INSTITUTE OF SCIENCE AND
TECHNOLOGY</h3>
<p style="color:DodgerBlue;">SCHOOL OF COMPUTING</p>
<p style="color:MediumSeaGreen;">DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING</p>
Border Colours:
<h1 style="border: 2px solid Tomato;">SoC</h1>
<h1 style="border: 2px solid DodgerBlue;">SIST</h1>
<h1 style="border: 2px solid Violet;">CSE</h1>
Borders:
<p class="dotted">A dotted border.</p>
<p class="dashed">A dashed border.</p>
<p class="solid">A solid border.</p>
<p class="double">A double border.</p>
<p class="groove">A groove border.</p>
<p class="ridge">A ridge border.</p>
<p class="inset">An inset border.</p>
<p class="outset">An outset border.</p>
<p class="none">No border.</p>
<p class="hidden">A hidden border.</p>
<p class="mix">A mixed border.</p>
<p class="mixed">A Mixed border with margins.</p>
</body>
</html>
CSS Margins
• The CSS margin properties are used to create space around elements, outside of any
defined borders.
• CSS provides full control over the margins. There are properties for setting the margin
for each side of an element (top, right, bottom, and left).
• CSS has properties for specifying the margin for each side of an element:
o margin-top
o margin-right
o margin-bottom
o margin-left
• All the margin properties can have the following values:
o auto - the browser calculates the margin. horizontally center the element within
its container. The element will then take up the specified width, and the
remaining space will be split equally between the left and right margins
o length - specifies a margin in px, pt, cm, etc.
o % - specifies a margin in % of the width of the containing element
o inherit - specifies that the margin should be inherited from the parent element
o Negative values are allowed.
Padding
• The CSS padding properties are used to generate space around an element's content,
inside of any defined borders.
• CSS provides full control over the padding. There are properties for setting the
padding for each side of an element (top, right, bottom, and left).
• CSS has properties for specifying the padding for each side of an element:
o padding-top
o padding-right
o padding-bottom
o padding-left
• All the padding properties can have the following values:
o length - specifies a padding in px, pt, cm, etc.
o % - specifies a padding in % of the width of the containing element
o inherit - specifies that the padding should be inherited from the parent element
o Negative values are not allowed.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
background-color: green;
color: white;
font-family: verdana;
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
p{
margin: 25px 50px 75px 100px;
padding: 25px 50px 75px 100px;
}
h1 {
margin: 25px 50px 75px; /* top, (left and right), bottom */
padding: 25px 50px 75px;
}
h2 {
margin: 25px 50px; /* top and bottom, left and right */
padding: 25px 50px;
}
h4 {
margin: 25px; /* all four margins */
padding: 25px;
}
p.mpClass {
width: 300px;
padding: 25px;
box-sizing: border-box;
}
div.hwClass {
max-width: 500px;
height: 100px;
background-color: powderblue;
}
</style>
</head>
<body>
<h1>Margin and Padding - top, (left and right), bottom</h1>
<h2>Margin and Padding - top and bottom, left and right</h2>
<h4>All Four Margins and Padding</h4>
<div>This div element has a Top margin of 100px. <br><br> Right margin of 150px <br><br>
Bottom margin of 100px <br><br> Left margin of 80px. <br><br>
Padding set to: Top: 50px, Right: 30px, Bottom: 50px, Left: 80px.</div>
<p>Shorthand margin</p>
<div class="hwClass"></div>
<p class="mpClass">Test</p>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<p>The CSS box model is essentially a box that wraps around every HTML element. It
consists of: borders, padding, margins, and the actual content.</p>
<div>This text is the actual content of the box. Added a 25px padding, 25px margin and a
25px green border. </div>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid gray;
padding: 8px;
}
h1 {
text-align: center;
text-transform: uppercase;
color: #4CAF50;
}
p{
text-indent: 50px;
text-align: justify;
letter-spacing: 3px;
line-height: 2.0;
}
a{
text-decoration: underline; /*overline, line-through;*/
color: #008CBA;
}
p.upper {
text-transform: uppercase; /* lowercase, capitalize */
letter-spacing: 5px;
word-spacing: 10px;
text-shadow: 1px 2px red;
}
p.dirrtl {
direction: rtl;
}
p.ffly {
font-family: "Times New Roman", Times, serif, verdana;
font-style: oblique; /* italics, normal */
font-size: 40px;
font-weight: bold;
font-variant: small-caps;
}
</style>
</head>
<body>
<div>
<h1>text formatting</h1>
<p>This text is styled with some of the text formatting properties. The heading uses the text-
align, text-transform, and color properties.
The paragraph is indented, aligned, and the space between characters is specified. The
underline is removed from this colored
<a target="_blank" href="#">"Try it Yourself"</a> link.</p>
<p class="upper">Displays the text in uppercase</p>
<p class="dirrtl"><bdo dir="rtl">Displays the text in left to right. BDO - Bidirectional Text
Overried Element</bdo></p>
<p class="ffly">Demonstrate Font Families</p>
</div>
</body>
</html>
Transformations – 2D and 3D
CSS transforms allow you to translate, rotate, scale, and skew elements.
A transformation is an effect that lets an element change shape, size and position.
CSS supports 2D and 3D transformations.
2D transformation methods:
• translate()
• rotate()
• scale()
• skewX()
• skewY()
• matrix()
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 300px;
height: 100px;
background-color: yellow;
border: 1px solid black;
transform: translate(50px,100px); /* Standard syntax */
}
div#myDiv {
transform: rotate(20deg);
}
div#myScale {
transform: scale(2,3); /* Standard syntax */
}
div#myScale1 {
transform: scale(.5,.5); /* Standard syntax */
}
div#myskew {
transform: skewX(20deg); /* Standard syntax */
/* skewX, skewY(deg), skew(20deg, 20deg) */
}
div#tMatrix {
transform: matrix(1, -0.3, 0, 1, 0, 0);
}
</style>
</head>
<body>
<div>
This div element is moved 50 pixels to the right, and 100 pixels down from its current
position.
</div>
<div>
This a normal div element.
</div>
<div id="myDiv">
This div element is rotated clockwise 20 degrees.
</div>
<div id="myScale">
This div element is rotated clockwise 20 degrees.
</div>
<div id="myScale1"> transform: scale(0.5, 0.5);
</div>
<div id="myskew">The skewX() method skews an element along the X-axis by the given
angle.</div>
<div id="tMatrix">
The matrix() method combines all the 2D transform methods into one.
The matrix() method take six parameters, containing mathematic functions, which allows you
to rotate, scale, move (translate), and skew elements.
Animation
<!DOCTYPE html>
<html>
<head>
<style>
/* Draw Box */
#mainBorder {
position:relative;
width:500px;
height:400px;
margin:0 auto 10px;
border:1px #aaa solid;
padding:10px;
}
/* Blue Dots */
#blue1, #blue2, #blue3, #blue4, #blue5, #blue6, #blue7, #blue8 {
width: 20px;
height: 20px;
border-radius: 10px;
position: absolute;
top: 40px;
left: 40px;
background-color: blue;
transition: all 2s ease-in-out;
transform: translate3d(0,0,0);
}
#blue1 {
transition-delay: 0.1s;
}
#blue2 {
transition-delay: 0.2s;
}
#blue3 {
transition-delay: 0.3s;
}
#blue4 {
transition-delay: 0.4s;
}
#blue5 {
transition-delay: 0.5s;
}
#blue6 {
transition-delay: 0.6s;
}
#blue7 {
transition-delay: 0.7s;
}
#blue8 {
transition-delay: 0.8s;
}
/* Top Left Diagonal */
#redBall:hover #blue1, #redBall.hover_effect #blue1 {
transform: translate(-250px,-200px);
}
/* Top */
#redBall:hover #blue2, #redBall.hover_effect #blue2 {
transform: translate(0,-200px);
}
/* Right */
#redBall:hover #blue4, #redBall.hover_effect #blue4 {
transform: translate(250px, 0);
}
/* Bottom */
#redBall:hover #blue6, #redBall.hover_effect #blue6 {
transform: translate(0,200px);
}
/* Left */
#redBall:hover #blue8, #redBall.hover_effect #blue8 {
transform: translate(-250px,0);
}
</style>
</head>
<body>
<div id="mainBorder">
<div id="redBall" class="hover">
<div id="blue1"></div>
<div id="blue2"></div>
<div id="blue3"></div>
<div id="blue4"></div>
<div id="blue5"></div>
<div id="blue6"></div>
<div id="blue7"></div>
<div id="blue8"></div>
</div>
</div>
</body>
</html>