WD 3
WD 3
(AUTONOMOUS)
VANIYAMBADI
PG and Department of Computer Science
3nd BSC CS
Semester- VI
E Notes(StudyMaterial)
Unit: 3–
XML & DHTML: Cascading style sheet (CSS)-what is CSS-Why we use CSS-adding CSS to
your web pages-Grouping styles-extensible markup language (XML).
Learning Objectives: Understand and apply the concepts of XML and DHTML
Course Outcome: Ability to optimize page styles and layout with Cascading
Style Sheets (CSS).
DHTML Tutorial
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
Dynamic HTML is not a markup or programming language but it is a term that combines the
features of various web development technologies for creating the web pages dynamic and
interactive.
The DHTML application was introduced by Microsoft with the release of the 4 th version of IE
(Internet Explorer) in 1997.
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for controlling
the style and layout of the HTML elements on the web pages.
JavaScript
JavaScript is a scripting language which is done on a client-side. The various browser supports
JavaScript technology. DHTML uses the JavaScript technology for accessing, controlling, and
manipulating the HTML elements. The statements in JavaScript are the commands which tell the
browser for performing an action.
DOM
DOM is the document object model. It is a w3c standard, which is a standard interface of
programming for HTML. It is mainly used for defining the objects and properties of all elements
in HTML.
Uses of DHTML
Following are the uses of DHTML (Dynamic HTML):
o It is used for designing the animated and interactive web pages that are developed in real-
time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh their content
automatically.
Features of DHTML
Following are the various characteristics or features of DHTML (Dynamic HTML):
o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color, and content
of a web page.
o It provides the facility for using the events, methods, and properties. And, also provides
the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or web pages.
o With the help of DHTML, users can easily change the tags and their properties.
o The web page functionality is enhanced because the DHTML uses low-bandwidth effect.
Difference between HTML and DHTML
Following table describes the differences between HTML and DHTML:
4. It does not contain any server-side 4. It may contain the code of server-side
scripting code. scripting.
5. The files of HTML are stored with the 5. The files of DHTML are stored with the
.html or .htm extension in a system. .dhtm extension in a system.
6. A simple page which is created by a user 6. A page which is created by a user using
without using the scripts or styles called as the HTML, CSS, DOM, and JavaScript
an HTML page. technologies called a DHTML page.
7. This markup language does not need 7. This concept needs database connectivity
database connectivity. because it interacts with users.
DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as dynamic. We
can easily type the JavaScript code within the <head> or <body> tag of a HTML page. If we want
to add the external source file of JavaScript, we can easily add using the <src> attribute.
Following are the various examples, which describes how to use the JavaScript technology with
the DHTML:
Document.write() Method
The document.write() method of JavaScript, writes the output to a web page.
Example 1: The following example simply uses the document.write() method of JavaScript in
the DHTML. In this example, we type the JavaScript code in the <body> tag.
1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>
Test it Now
Output:
JavaScript and HTML event
A JavaScript code can also be executed when some event occurs. Suppose, a user clicks an HTML
element on a webpage, and after clicking, the JavaScript function associated with that HTML
element is automatically invoked. And, then the statements in the function are performed.
Advertisement
Example 1: The following example shows the current date and time with the JavaScript and
HTML event (Onclick). In this example, we type the JavaScript code in the <head> tag.
1. <html>
2. <head>
3. <title>
4. DHTML with JavaScript
5. </title>
6. <script type="text/javascript">
7. function dateandtime()
8. {
9. alert(Date());
10. }
11. </script>
12. </head>
13. <body bgcolor="orange">
14. <font size="4" color="blue">
15. <center> <p>
16. Click here # <a href="#" onClick="dateandtime();"> Date and Time </a>
17. # to check the today's date and time.
18. </p> </center>
19. </font>
20. </body>
21. </html>
Test it Now
Output:
Explanation:
In the above code, we displayed the current date and time with the help of JavaScript in DHTML.
In the body tag, we used the anchor tag, which refers to the page itself. When you click on the link,
then the function of JavaScript is called.
In the JavaScript function, we use the alert() method in which we type the date() function. The
date function shows the date and time in the alert dialog box on the web page.
Example 1: This example checks the Grade of a student according to the percentage criteria with
the JavaScript and HTML DOM. In this example, we type the code of a JavaScript in the <body>
tag.
1. <html>
2. <head>
3. <title> Check Student Grade
4. </title>
5. </head>
6.
7. <body>
8. <p>Enter the percentage of a Student:</p>
9. <input type="text" id="percentage">
10. <button type="button" onclick="checkGrade()">
11. Find Grade
12. </button>
13. <p id="demo"></p>
14. <script type="text/javascript">
15. function checkGrade() {
16. var x,p, text;
17. p = document.getElementById("percentage").value;
18.
19. x=parseInt(p);
20.
21.
22. if (x>90 && x <= 100) {
23. document.getElementById("demo").innerHTML = "A1";
24. } else if (x>80 && x <= 90) {
25. document.getElementById("demo").innerHTML = "A2";
26. } else if (x>70 && x <= 80) {
27. document.getElementById("demo").innerHTML = "A3";
28. }
29. }
30. </script>
31. </body>
32. </html>
Test it Now
Output:
Explanation:
In the above code, we check the student’s Grade with the help of JavaScript in DHTML. In the
JavaScript code, we used the checkGrade() method, which is invoked when we click on the button.
In this function, we stored the value in variable p. The value is taken in the input field. When the
value is stored, then we convert the value of p into integer and store the conversion value in x,
because the value in p is text.
After that, we used the if-else-if statement for finding the grade according to the percentage.
1. <html>
2. <head>
3. <title>
4. getElementById.style.property example
5. </title>
6. </head>
7. <body>
8. <p id="demo"> This text changes color when click on the following different buttons. </p>
9. <button onclick="change_Color('green');"> Green </button>
10. <button onclick="change_Color('blue');"> Blue </button>
11. <script type="text/javascript">
12.
13. function change_Color(newColor) {
14. var element = document.getElementById('demo').style.color = newColor;
15. }
16. </script>
17. </body>
18. </html>
Test it Now
Output:
Explanation:
In the above code, we changed the color of a text by using the following syntax:
1. document.getElementById('demo').style.property=new_value;.
The above syntax is used in the JavaScript function, which is performed or called when we clicked
on the HTML buttons. The different HTML buttons specify the color of a text.
DHTML CSS
We can easily use the CSS with the DHTML page with the help of JavaScript and HTML DOM.
With the help of this.style.property=new style statement, we can change the style of the currently
used HTML element. Or, we can also update the style of any particular HTML element
by document.getElementById(id).style.property = new_style statement.
Example 1: The following example uses the DHTML CSS for changing the style of current
element:
1. <html>
2. <head>
3. <title>
4. Changes current HTML element
5. </title>
6. </head>
7. <body>
8. <center>
9. <h1 onclick="this.style.color='blue'"> This is a JavaTpoint Site </h1>
10. <center>
11. </body>
12. </html>
Test it Now
Output:
Explanation:
In the above code, we used the this.style.color='blue' statement, which shows the color of a text
as blue.
Example 2: The following example uses the DHTML CSS for changing the style of the HTML
element:
1. <html>
2. <head>
3. <title>
4. changes the particular HTML element example
5. </title>
6. </head>
7. <body>
8. <p id="demo"> This text changes color when click on the following different buttons. </p>
9. <button onclick="change_Color('green');"> Green </button>
10. <button onclick="change_Color('blue');"> Blue </button>
11. <script type="text/javascript">
12.
13. function change_Color(newColor) {
14. var element = document.getElementById('demo').style.color = newColor;
15. }
16. </script>
17. </body>
18. </html>
Test it Now
Output:
Explanation:
DHTML Events
An event is defined as changing the occurrence of an object.
It is compulsory to add the events in the DHTML page. Without events, there will be no dynamic
content on the HTML page. The event is a term in the HTML, which triggers the actions in the
web browsers.
Suppose, any user clicks an HTML element, then the JavaScript code associated with that element
is executed. Actually, the event handlers catch the events performed by the user and then execute
the code.
Example of events:
1. Click a button.
2. Submitting a form.
3. An image loading or a web page loading, etc
Introductionof CSS
CSS stands for Cascading Style Sheets. It is a simple design language intended
to simplify the process of making web pages presentable. CSS handles the look and
feel part of a web page. Using CSS, you can control the color of the text, the style
of fonts, the spacing between paragraphs, how columns are sizedand laid out, what
background images or colors are used, as well as a variety of other effects.
CSS works with HTML and other Markup Languages (such as XHTML and
XML) to control the way the content is presented. Cascading Style Sheets is a means
to separate the appearance of a webpage from the content of a webpage.
Definition
Advantages
Whatisthe“Cascade”partof CSS?
The cascade part of CSS means that more than one style sheet can be
attached to a document, and all of them can influence the presentation. For example,
a designer can have a global style sheet for the whole site, but a localone for say,
controlling the link color and background of a specific page. Or, a user can use own
style sheet if s/he has problems seeing the page, or if s/he just prefers a certain look.
CSSSyntax
Selector{property:
Example:Youcandefineaheadingasfollows:
h1 {color:red;font-size:15px}
Hereh1isaselector,colorandfont-sizearepropertiesandthe given
value red, and 15px are the value of that property.
Theselectoris normallytheHTMLelementyou want to style.
Eachdeclaration consistsof apropertyand avalue.
Thepropertyisthestyleattributeyouwanttochange.Eachpropertyhas a value.
Rules/PrincipleofCSS
1. Every statement must have a selector and a declaration. The declaration
comes immediately after the selector and is contained in a pair of curly
braces.
2. Thedeclaration is oneormoreproperties separated bysemicolons.
3. Each property has a property name followed by a colon and then the value
for that property. There are many different types of values, but any given
property can only take certain values as set down in the specification.
4. Sometimes a property can take a number of values, as in the font-family.
The values in the list should be separated by a comma and a space.
5. Sometimesavaluewillhaveaunitaswellastheactualvalue,asinthe
1.3em.You must not putaspacebetween thevalueand its unit.
6. AswithHTML,whitespace canbeusedtomake your style sheet easier to read
and write.
Partsofstylesheet
A style sheet consists of one or more rules that describe how
document elements should be displayed. A rule in CSS has two parts: the
selector and the declaration. The declaration also has two parts, the
propertyandthevalue.Let'stakealookataruleforaheading1style:h1
{font-family:verdana, "sansserif";font-size:1.3em}Thisexpressionisa rule
that says every h1 tag will be verdana or other sans-serif font and the
fontsize will be 1.3em. Let's take a look at the different parts of this rule.
Selector
{
property1:somevalue;
property2:some value;
}
The declaration contains the property and value for the selector. The property is the
attribute you wish to change and each property can take a value. The property and
value are separated by a colon and surrounded by curly braces:
body{background-color:black}
If the value of a property is more than one word, put quotes around that value: body
{ font-family: "sans serif"; } If you wish to specify more than one property, you
must use a semi-colon to separate each property. This rule defines aparagraph that
will have blue text that is centered.
p{text-align:center;color:blue}
You can group selectors. Separate each selector with a comma. The example below
groups headers 1, 2, and 3 and makes them all yellow. h1,h2,h3{ color: yellow}
Checkyourprogress1
Q1.Writetheabbreviation ofCSS?
Answer:
Q2.Writethethreeparts of CSSsyntax?
Answer:
CSSSelectors
#welcome
{
color:red;
text-align:center;
}
TheClass selectors
Theclass selectoris used to specifyastylefor a group ofelements. Unlike the
id selector, the class selector is most often used on several elements.
Thisallows youtosetaparticularstyleformanyHTMLelementswiththe same
class. The class selector uses the HTML class attribute, and is defined with
a ".". In the example below, all HTML elements with class="center" will be
center-aligned:
Imaginewithinthebodyelementofourhtmlpage,wehavethefollowing header
element
<h2class=”center”>Summary</h2>
Wecanthencreate aCSSrulewiththeclass selector:
center{text-align:center;}
Youcan also specifythat onlyspecificHTMLelements should beaffected by
a class. In the example below, all p elements with class="center" willbe
center-aligned: example
p.center{text-align:center;}
SomeoftheotherselectorsareusedinCSS,theyare:
3.3.3.1 Universal selector
An asterisk (*) is the universal selector for CSS.It matches a single element
of any type. Omitting the asterisk with simple selectors has the same effect.
For instance, *.warning and. warning are considered equal. Rather than
selecting elements of a specific type, the universal selector quite simply
matches the name of any element type: Example-
*
{ Color:#000000;
}
Thisrulerendersthecontentofeveryelementinourdocumentinblack.
3.3.3.2AttributeSelector
You can also apply styles to HTML elements with particular attributes. The
style rule below will match all the input elements having a type attribute
with a value of text:
input[type="text"]
{
color:#000000;
}
The advantage to this method is that the <input type="submit" /> element
isunaffected,andthecolorappliedonlytothedesiredtextfields.Thereare
following rules applied to attribute selector.
p[lang]-Selectsallparagraphelementswithalangattribute.
p[lang="fr"] - Selects all paragraph elements whose lang attribute
has a value of exactly "fr".
p[lang~="fr"] - Selects all paragraph elements whose lang attribute
contains the word "fr".
p[lang|="en"] - Selects all paragraph elements whose lang attribute
contains values that are exactly "en", or begin with "en-".
Checkyourprogress2
Q2.Whatisuniversalselector?.
Answer:
Waystoinsert CSS
Therearethreewaysofinsertingastyle sheet:
1. Externalstylesheet
2. Internalstylesheet
3. Inlinestyle
Externalstylesheet
An external style sheet is ideal when the style is applied to many pages.
With an external style sheet, you can change the look of an entire Web site by
changingonefile.Eachpagemustlinktothestylesheetusingthe<link> tag.The
<link>taggoes insidethehead section:
<head>
<linkrel="stylesheet"type="text/css"href="mystyle.css"/>
</head>
An external style sheet can be written in any text editor. The file should not contain
any html tags. Your style sheet should be saved with a .css extension. An example
of a style sheet file is shown below:
hr{color:sienna;}
p{margin-left:20px;}
body{background-image:url("images/back40.gif");}
Notes :Do not leave spaces between the property value and the units! "margin-
left:20 px" (instead of "margin- left:20px") will work in IE, but not in Firefox or
Opera.
Internalstylesheet
An internal style sheet should be used when a single document has a unique
style. You define internal styles in the head section of an HTML page, by using the
<style> tag, like this:
<head>
<styletype="text/css">
hr{color:sienna;}
p{margin-left:20px;}
body{background-image:url("images/back1.gif");}
</style>
</head>
Inlinestylesheet
An inline style loses many of the advantages of style sheets by mixing
content with presentation. Use this method sparingly!To use inline styles you use
the style attribute in the relevant tag. The style attribute can contain any CSS
property. The example shows how to change the color and the left margin of a
paragraph:
<pstyle="color:sienna;margin-left:20px">Thisisa paragraph.</p>
Backgroundimagehandling
Thebackground-imagepropertyspecifiesanimagetouseasthebackgroundofan element.
By default, the image is repeated so it covers the entire element. The background
image for a page can be set like this:body {background- image:url('paper.gif');}
Example
<html>
<head>
<Title>ThisismyInternalcsspage</Title>
<styletype="text/css">body
{
background-image:url
("C:/Users/SAI/Desktop/Desktop/100MSDCF/11. jpg");
}
</style>
</head>
<body>
BackgroundImage
</body>
</html>
Theoutput of theaboveexampleis :
Youcanset the followingbackgroundpropertiesofan element:
Thebackground-imagepropertyisusedtosetthebackgroundimageof an
element.
Thebackground-repeatpropertyisusedtocontroltherepetitionofan
image in the background.
Thebackground-positionpropertyisusedtocontrolthepositionofan
image in the background.
Thebackground-attachmentpropertyisusedtocontrolthescrollingof an
image in the background.
Thebackgroundpropertyisusedasshorthandtospecifyanumberofother
background properties.
RepeattheBackgroundImage
The following example demonstrates how to repeat the background image
if an image is small. You can use no-repeat value for the background-repeat
property if you don't want to repeat an image. In this case, the image will display
only once. By default, the background-repeat property will have a repeat value.
<tablestyle="background-image:url(/https/www.scribd.com/images/pattern1.gif);background-repeat:
repeat;">
<tr><td>
Thistablehasbackground image whichrepeatsmultipletimes.
</td></tr>
</table>
Thefollowingexamplewhichdemonstrateshow torepeatthebackground image
vertically.
<tablestyle="background-image:url(/https/www.scribd.com/images/pattern1.gif);background-repeat:
repeat-y;">
<tr><td>
Thistablehasbackgroundimagesetwhichwillrepeatvertically.</td></tr>
</table>
Thefollowingexampledemonstrateshowtorepeatthebackgroundimage
<tablestyle="background-image:url(/https/www.scribd.com/images/pattern1.gif);background-repeat:
repeat-x;">
<tr><td>
Thistablehasbackgroundimagesetwhichwillrepeathorizontally.</td></tr>
</table>
horizontally.
SettheBackgroundImage Position
Thefollowingexampledemonstrateshowtosetthebackgroundimageposition 100
pixels away from the left side.
<tablestyle="background-image:url(/https/www.scribd.com/images/pattern1.gif);
background-position:100px;">
<tr><td>
Backgroundimagepositioned 100pixelsawayfromtheleft.
</td></tr>
</table>
Checkyourprogress3
Q2.Writethe backgroundpropertiesofCSS.
Answer:
BackgroundcolourManagementusingCSS
body{background-color:#b0c4de;}
<pstyle="background-color:yellow;">
Thistexthasayellowbackgroundcolor. </p>
WithCSS,acolorismostoftenspecifiedby:
1. aHEXvalue -like"#ff0000"
2. an RGBvalue-like"rgb(255,0,0)"
3. acolor name -like"red"
Intheexamplebelow,theh1,p,anddivelementshavedifferentbackground colors:
h1 {background-color:#6495ed;}
p {background-
color:#e0ffff;}div{background-
Example color:#b0c4de;}
CSSColors -Hex Codes
A hexadecimal is a 6 digit representation of a color. The first two digits (RR)
represent a red value, the next two are a green value (GG), and the last are the blue
value (BB). Each hexadecimal code will be preceded by a pound or hash sign ‘#’.
Following are the examples to use Hexadecimal notation.
This color value is specified using the rgb( ) property. This property takes
three values, one each for red, green, and blue. The value can be an integer between
0 and 255 or a percentage. NOTE: All the browsers does not support rgb() property
of color, so it is recommended not to use it.
TextManagementusingCSS
SettheText Color
Thefollowingexampledemonstrateshowtosetthetextcolor.Possible value
could be any color name in any valid format.
<pstyle="color:red;">Thistextwillbewritteninred.</p>
SettheText Direction
Thefollowingexampledemonstrateshowtosetthedirectionofatext. Possible
values are ltr or rtl.
<pstyle="direction:rtl;">Thistextwillberenderedfromrighttoleft</p>
3.7.3.SettheSpacebetweenCharacters
<pstyle="letter-spacing:5px;">Thistextishavingspacebetweenletters.
</p>
SettheSpacebetweenWords
Thefollowingexampledemonstrateshowtosetthespacebetweenwords.
Possible values are normal or a number specifying space.
<pstyle="word-spacing:5px;">Thistextishavingspacebetweenwords.
</p>
SettheText Indent
The following example demonstrates how to indent the first line of a
paragraph.Possiblevaluesare%oranumberspecifyingindentspace.
<pstyle="text-indent:1cm;">
Thistextwillhavefirstlineindentedby1cmandthislinewill remain at
its actual position this is done by CSS text-indent property.
</p>
SettheText Alignment
Thefollowingexampledemonstrateshowtoalignatext.Possiblevalues are
left, right, center, justify.
<pstyle="text-align:right;">Thiswillberightaligned.</p>
<pstyle="text-align:center;">Thiswillbecenteraligned.</p>
<pstyle="text-align:left;">Thiswillbeleftaligned.</p>
DecoratingtheText
<pstyle="text-decoration:underline;">Thiswillbeunderlined</p>
<pstyle="text-decoration:line-through;">Thiswillbestrikedthrough.
</p>
<pstyle="text-decoration:overline;">Thiswillhaveaoverline.</p>
<pstyle="text-decoration:blink;">Thistextwillhaveblinkingeffect</p>
SettheTextCases
Thefollowingexampledemonstrateshowtosetthecasesforatext. Possible
values are none, capitalize, uppercase, lowercase.
<pstyle="text-transform:capitalize;">Thiswillbecapitalized</p>
<pstyle="text-transform:uppercase;">Thiswillbeinuppercase</p>
<pstyle="text-transform:lowercase;">Thiswillbeinlowercase</p>
Example
:
Theoutputof theaboveprogramis :
FontManagementusingCSS
Afontis the combination of typeface and other qualities, such as size, pitch, and
spacing. For example, Times Roman is a typeface that defines the shapeof each
character. Within Times Roman, however, there are manyfontsto choosefrom -
-differentsizes,italic,bold,andsoon.Youcansetthefollowing font properties of an
element:
SettheFont Family
Followingistheexample,whichdemonstrateshowtosetthefontfamily of an
element. Possible value could be any font family name.
<pstyle="font-family:georgia,garamond,serif;">
Thistextisrenderedineithergeorgia,garamond, orthedefaultseriffont
depending on which fontyou have at your system. </p>
SettheFontStyle
Thefollowingexampledemonstrateshowtosetthefontstyleofan element.
Possible values are normal, italic and oblique.
<pstyle="font-style:italic;">Thistextwillberenderedinitalic style
</p>
SettheFontVariant
Thefollowingexampledemonstrateshowtosetthefontvariantofan element.
Possible values are normal and small-caps.
<pstyle="font-variant:small-caps;">Thistextwillberenderedassmall caps
</p>
SettheFontWeight
The following example demonstrates how to set the font weight of an
element. The font-weight property provides the functionality to specify how
bold a font is. Possible values could be normal, bold, bolder, lighter, 100,
200, 300, 400, 500, 600, 700, 800, 900.
<pstyle="font-weight:bold;">Thisfontisbold.</p>
<pstyle="font-weight:bolder;"> Thisfontisbolder.</p>
<pstyle="font-weight:900;">Thisfontis900weight.</p>
Setthe FontSize
The following example demonstrates how to set the font size of an
element. The font-size property is used to control the size of fonts.
Possiblevaluescouldbexx-small,x-small,small,medium,large,x-large, xx-
large, smaller, larger, size in pixels or in %.
SettheFontSize Adjust
The following example demonstrates how to set the font size adjust of an
element. This property enables you to adjust the x-height to make fonts more
legible. Possible value could be any number.
<pstyle="font-size-adjust:0.61;">Thistextisusingafont-size-adjust value.
</p>
SettheFontStretch
Theoutputof theaboveprogramis :
ManaginghyperlinksusingCSS
The:link signifiesunvisitedhyperlinks.
The:visited signifiesvisitedhyperlinks.
The:hoversignifies an element that currentlyhas theuser's mousepointer
hovering over it.
The:activesignifies an element on which theuser is currentlyclicking.
Usually, all these properties are kept in the header part of the HTML document.
Remember a:hover MUST come after a:link and a:visited in the CSS definition in
order to be effective. Also, a:active MUST come after a:hover in the CSS definition
as follows:
<styletype="text/css">
a:link{color:#000000}
a:visited {color: #006600}
a:hover {color: #FFCC00}
a:active{color: #FF00CC}
</style>
SettheColorofLinks
Thefollowingexampledemonstrateshowtosetthelinkcolor.Possible values
could be any color name in any valid format.
<styletype="text/css">
a:link{color:#000000}
</style>
<ahref="/html/index.htm">Black Link</a>
Thefollowingexampledemonstrateshowtosetthecolorofthevisited links.
Possible values could be any color name in any valid format.
<styletype="text/css">
a:visited{color:#006600}
</style>
<ahref="/html/index.htm">Clickthislink</a>
ChangetheColor ofLinkswhenMouseisOver
The following example demonstrates how to change the color of links when
we bring a mouse pointer over that link. Possible values could beany color
name in any valid format.
<styletype="text/css">
a:hover{color:#FFCC00}
</style>
<ahref="/html/index.htm">BringMouse Here</a>
ChangetheColor ofActiveLinks
Thefollowingexampledemonstrateshowtochangethecolorofactive links.
Possible values could be any color name in any valid format.
<styletype="text/css">
a:active{color: #FF00CC}
</style>
<ahref="/html/index.htm">ClickThis Link</a>
Checkyourprogress4
Q2.Whatarethedifferentpropertiesof Font ?
Answer:
Q3.Writethedifferentpropertiesof Hyperlink?
Answer:
ManagingListusingCSS
Lists are very helpful in conveying a set of either numbered or bulleted points.
Thischapterteaches youhowtocontrollisttype,position,style,etc.,usingCSS. We
have the following five CSS properties, which can be used to control lists:
Thelist-style-typeallowsyoutocontroltheshapeorappearanceofthe
marker.
The list-style-position specifies whether a long point that wraps to a
secondlineshouldalignwiththefirstlineorstartunderneaththestartof the
marker.
Thelist-style-imagespecifiesanimageforthemarkerratherthanabullet point
or number.
Thelist-styleservesas shorthand fortheprecedingproperties.
Themarker-offsetspecifiesthedistancebetweenamarkerandthetextin the
list.
Thelist-style-type Property
The list-style-type property allows you to control the shape or style of a bullet point
(also known as a marker) in case of unordered lists and the style of numbering
characters in ordered lists.Here are the values, which can be used for an unordered
list:
Value Description
None NA
disc Afilled-in
(default) circle
Circle An empty
circle
Square Afilled-in
square
Hereisanexample:
Theoutputof theaboveprogramis :
Thelist-style-position Property
The list-style-position property indicates whether the marker should
appearinsideoroutsideoftheboxcontainingthebulletpoints.Itcanhave one of
the two values:
Value Description
None NA
Inside If the text goes onto a second line, the text will wrap
underneaththemarker.Itwillalsoappearindentedtowhere
thetext would havestarted ifthe list had avalueofoutside.
Outside If the text goes onto asecondline, the text will bealigned
withthestart of thefirst line (to theright of the bullet).
Example:
<html>
<head>
<Title>Thisis myinlinecss page</Title>
</head>
<body>
<ulstyle="list-style-type:circle;list-stlye-
position:outside;"><li>Maths</li>
<li>SocialScience</li>
<li>Physics</li>
</ul>
<ulstyle="list-style-type:square;list-style-
position:inside;"><li>Maths</li>
<li>SocialScience</li>
<li>Physics</li>
</ul>
<olstyle="list-style-type:decimal;list-stlye-
position:outside;"><li>Maths</li>
<li>SocialScience</li>
<li>Physics</li>
</ol>
<olstyle="list-style-type:lower-alpha;list-style-position:inside;">
<li>Maths</li>
<li>SocialScience</li><li>Physics</li>
</ol>
</body>
</html>
Theoutputof theaboveprogramis :
DesigningTablesusing CSS
Theorder-collapse Property
<html>
<head>
<Title>Thisis myinlinecss page</Title>
</head>
<body>
<styletype="text/css">t
able.one
{border-collapse:collapse;}
table.two
{border-collapse:separate;}
td.a
{
border-style:dotted;
border-width:3px;
border-color:#000000;
padding: 10px;
}
td.b
{
border-style:solid;
border-width:3px;
border-color:#333333;
padding:10px;
}
</style>
<table class="one">
<caption>CollapseBorderExample</caption>
<tr><tdclass="a">CellACollapseExample</td></tr>
<tr><tdclass="b">CellBCollapseExample</td></tr>
</table><br/>
<table class="two">
<caption>SeparateBorder Example</caption>
<tr><tdclass="a">Cell ASeparateExample</td></tr>
<tr><tdclass="b">Cell BSeparateExample</td></tr>
</table>
</body>
</html>
Theoutputof theaboveprogramis :
Theborder-spacingProperty
Theempty-cells Property
Theempty-cellspropertyindicateswhetheracellwithout anycontentshouldhave a
border displayed.This property can have one of the three values- show, hide, or
inherit.Here is the empty-cells property used to hide borders of empty cells in the
<table> element.
Example:
<html>
<head>
<Title>Thisis myinlinecss page</Title>
</head>
<body>
<styletype="text/css">t
able.empty
{
width:350px;
border-collapse:separate;
empty-cells:hide;
}
td.empty
{
padding:5px;
border-style:solid;
border-width:1px;
border-color:#999999;}
</style>
<table class="empty">
<tr>
<th></th>
<th>Title one</th>
<th>Title two</th>
</tr>
<tr>
<th>RowTitle</th>
<tdclass="empty">value</td><tdclass="empty">value</td></tr>
<tr>
<th>RowTitle</th>
<tdclass="empty">value</td><tdclass="empty"></td>
</tr>
</table>
</body>
</html>
Theoutputof theaboveprogramis :
Checkyourprogress5
Q2.What are the different values of ordered and unordered list in css ?
Answer:
Workingwith BoxModel
You have seen the border that surrounds every box i.e. element, the padding that
can appear inside each box, and the margin that can go around them. In this chapter,
we will learn how to change the dimensions of boxes. We have the following
properties that allow you to control the dimensions of a box.
Theheightpropertyis used to set theheight of abox.
Thewidth propertyis used to set thewidth of abox.
Theline-heightpropertyis used toset theheightofalineof text.
The max-height property is used to set a maximum height that a box can
be.
The min-height property is used to set the minimum height that a box can
be.
The max-width property is used to set the maximum width that a box can
be.
The min-width property is used to set the minimum width that a box can
be.
TheHeight andWidthProperties
The height and width properties allow you to set the height and width for boxes.
They can take values of a length, a percentage, or the keyword auto. Here is an
example:
The line-height property allows you to increase the space between lines of text. The
value of the line-height property can be a number, a length, or a percentage. Here
is an example:
Themax-height Property
Themax-widthProperty
The max-width property allows you to specify the maximum width of a box. The
value of the max-width property can be a number, a length, or a percentage.
NOTE:ThispropertydoesnotworkineitherNetscape7or IE6. Here is an
example:
Theoutputof theabove program is
Theborderpropertiesallow youtospecifyhowtheborderoftheboxrepresenting an
element should look. There are three properties of a border you can change:
Theborder-colorspecifiesthecolorof a border.
Theborder-stylespecifieswhetherabordershouldbesolid,dashedline,
double line, or one of the other possible values.
Theborder-widthspecifiesthewidthof a border.
Theborder-color Property
The border-color property allows you to change the color of the border
surroundinganelement. Youcanindividuallychangethecolorofthebottom,left, top
and right sides of an element's border using the properties:
border-bottom-colorchangesthecolorofbottomborder.
border-top-colorchanges thecoloroftopborder.
border-left-colorchangesthecolorofleftborder.
border-right-colorchangesthecolorofrightborder.
Thefollowingexampleshowstheeffect of allthese properties:
Theoutputof theaboveprogramis :
Theborder-style Property
Youcanindividuallychangethestyleofthebottom,left,top,andrightbordersof an
element using the following properties:
border-bottom-stylechangesthestyleofbottomborder.
border-top-stylechangesthestyleoftopborder.
border-left-stylechangesthestyleofleftborder.
border-right-stylechangesthestyleofrightborder.
Itwillproducethefollowingresult:
DesigningoutlineusingCSS
NOTE:The outline properties are not supported byIE 6 or Netscape 7. You can
set the following outline properties using CSS.
Theoutline-width Property
The outline-width property specifies the width of the outline to be added to the box.
Its value should be a length or one of the values thin, medium, or thick, just like the
border-width attribute. A width of zero pixels means no outline. Here isan example:
Theaboveprogramwillproducethefollowingresult:
Theoutline-styleProperty
Theoutline-stylepropertyspecifiesthestylefortheline(solid,dotted,ordashed) that
goes around an element. It can take one of the following values:
none:Noborder.(Equivalentofoutline-width:0;)
solid:Outline is asingle solid line.
dotted:Outline isaseries of dots.
dashed:Outlineis aseries ofshort lines.
double: Outlineis two solid lines.
groove:Outlinelooksas thoughitis carvedintothepage.
ridge:Outline looks theopposite of groove.
inset:Outlinemakes theboxlooklikeit isembedded inthepage.
outset:Outlinemakes theboxlooklike itis comingout ofthecanvas.
hidden:Sameasnone.
Hereisanexample:
Theaboveprogramwillproducethefollowingresult:
Theoutline-colorProperty
The outline-color property allows you to specify the color of the outline. Its value
should eitherbe acolorname,a hex color, or an RGBvalue, as with the colorand
border-color properties.Here is an example:
Theaboveprogramwillproducethefollowingresult:
SettingPageMarginusing CSS
TheMarginProperty
Themarginpropertyallowsyoutosetallofthepropertiesforthefour margins in
one declaration. Here is the syntax to set margin around a paragraph:
<styletype="text/css">
p {margin: 15px}
allfour marginswill be15px
p {margin: 10px2%}
topandbottommarginwillbe10px,leftandrightmarginwillbe2%ofthetotal width of
the document.
p{margin: 10px2%-10px}
topmarginwillbe10px,leftandrightmarginwillbe2%ofthetotalwidthofthe document,
bottom margin will be -10px
Hereisanexample:
Theaboveprogramwillproducethefollowingresult:
Themargin-bottom Property
Themargin-leftpropertyallowsyoutosettheleftmarginofanelement.Itcan have a
value in length, %, or auto. Here is an example:
Theaboveprogramwillproducethefollowingresult
Checkyourprogress6
Q1.Writethedifferentpropertiesofthedimensionsof abox.
Answer:
Q2.Writethethreepropertiesof border.
Answer:
Q4.Whatis amarginproperty?
Answer:
Q5.Writetheborder-stylepropertyin CSS.
Answer:
Letus sumup
Inthisunitwehaveunderstoodwhatis CSS,advantagesof CSS,
PartsofCSS,CSSsyntax,CSSselectors,waystoinsertCSS,background image
handling, background colourmanagement, text management,
fontmanagement,managinghyperlinks,managinglists,designingtables, working
with box model, designing borders, designing outline,
settingpage margin
Reference
1. W3Schools.com
2. Google.com
3. Tutorialpoints.com
Checkyourprogresspossibleanswers
Checkyourprogress1
Q1.WritetheabbreviationofCSS?
Answer
Checkyourprogress2
Q1.Whatarethe3typesofselectors.
Answer
Q2.Whatisuniversalselector?. Answer
Universal selector
Anasterisk(*)istheuniversalselectorforCSS.Itmatchesasingleelementofany type.
Omitting the asterisk with simple selectors has the same effect. For
instance,*.warningand.warningareconsideredequal.Ratherthanselectingelements of a
specific type
Checkyourprogress3
Q1.Howmanywaystobuildstylesheet?whatarethey?
Answer
Therearethree ways ofinsertingastylesheet:
1. Externalstylesheet
2. Internalstylesheet
3. Inlinestyle
Q2.WritethebackgroundpropertiesofCSS
Answer
Q1.Whatistherepresentationof6digitHexacode? Answer
A hexadecimal is a 6 digit representation of a color. The first two digits (RR)
representaredvalue,thenexttwoareagreenvalue(GG),andthelastaretheblue value (BB).
Each hexadecimal code will be preceded by a pound or hash sign ‘#’. Following are
the example to use Hexadecimal notation.
#66AA77
Q2.WhatarethedifferentpropertiesofFont?
Answer
Fontproperties ofanelement:
Thefont-familypropertyisused tochangethefaceofa font.
Thefont-stylepropertyis used tomakeafontitalic oroblique.
Thefont-variantpropertyisused to createasmall-caps effect.
Thefont-weightpropertyisusedtoincreaseordecreasehowboldorlightafont appears.
Thefont-sizepropertyisusedto increaseor decreasethe sizeof a font.
Thefontpropertyis usedas shorthandto specifyanumberofother fontproperties.
Q3.WritethedifferentpropertiesofHyperlink? Answer
Propertiesofahyperlink:
The:link signifiesunvisitedhyperlinks.
The:visited signifiesvisitedhyperlinks.
The:hoversignifiesanelementthatcurrentlyhastheuser'smousepointerhovering over
it.
The:activesignifies an element on which theuser is currentlyclicking.
Checkyourprogress5
Q1.Whatisthedifferentpropertiesoftableincss? Answer
Followingproperties ofatable:
Theborder-collapsespecifieswhetherthebrowsershouldcontroltheappearanceof the
adjacent borders that touch each other or whether each cell should maintain its style.
Theborder-spacing specifiesthewidththatshouldappearbetweentable cells.
Thecaption-sidecaptionsarepresentedinthe<caption>element.Bydefault,these are
rendered above the table in the document. You use the caption-side property to
control the placement of the table caption.
Theempty-cells specifywhetherthe border shouldbeshown ifacell is empty.
The table-layout allows browsers to speed up the layout of a table by using the first
widthpropertiesitcomesacrossfortherestofacolumnratherthanhavingtoloadthe whole
table before rendering it.
Thevalues,foranunorderedlist: disc
(default),Circle,Square.
Decimal,decimal-leading-zero,lower-alpha,upper-alpha,lower-roman,upper-roman.
Checkyourprogress6
Theborder-colorspecifiesthecolorof a border.
Theborder-stylespecifieswhetherabordershouldbesolid,dashedline,doubleline, or one
of the other possible values.
Theborder-widthspecifiesthewidthof a border
Q3.WritethefewmajordifferenceofoutlineinCSS. Answer
Therearefewmajordifferencesare:
Anoutlinedoes not take up space.
Outlinesdo not haveto be rectangular.
Outlineisalwaysthesameonallsides;youcannotspecifydifferentvaluesfor
different sides of an element.
Q4.Whatisamarginproperty?
Answer
Followingpropertiestosetanelementmargin.
1. Themarginspecifiesashorthandpropertyforsettingthemarginpropertiesin one
declaration.
2. Themargin-bottomspecifiesthebottommarginofan element.
3. Themargin-topspecifiesthetopmarginof anelement.
4. Themargin-leftspecifiestheleftmarginofanelement.
5. Themargin-rightspecifiestherightmarginofanelement
Q5.Writetheborder-stylepropertyinCSS.
Answer
Theborder-styleproperty:
none:Noborder.(Equivalentofborder-width:0;)
solid:Border is asinglesolid line.
dotted:Borderisaseriesof dots.
dashed:Borderis aseries ofshort lines.
double:Borderistwosolid lines.
groove:Borderlooksasthough itiscarvedintothe page.
ridge:Border looks the opposite of groove.
inset:Bordermakesthe boxlooklikeitisembeddedinthepage.
outset:Bordermakesthe boxlooklike itiscomingoutofthecanvas.
hidden:Sameasnone,exceptintermsofborder-conflict
resolution for table elements.
Unit -4
CSS Advanced
Learningobjectives:
AftertheCompletion ofthisunityoushouldbeableto know
ParagraphPadding
Imageheightandwidth setting
Blocklevelandinline elements
Pseudo-classand elements
Various attributeof image
Differentattributevalues ofselectors
Structure
PaddingusingCSS
Thepadding-bottom Property
Thepadding-topProperty
SettingDisplayUsingCSS
Block-levelElements
Inlineelement
SettingWidth And MaxWidth usingCSS
SettingPosition usingCSS
RelativePositioning
AbsolutePositioning
FixedPositioning
Settingthe Float PropertyusingCSS
Element float
TurningoffFloat-UsingClear
All CSS float
InlineBlock property
HorizontalAlignmentinCSS
CenterAlign Elements
Centeralignment Text
Centeranimage
LeftandRightAlign -Usingposition
WorkingWithCombinatory
DescendantSelector
Child Selector
AdjacentSibling Selector
Generalsiblingselector
Workingwith Pseudo-class
AnchorPseudo-classes
Pseudoclassesand CSS classes
SimpleTooltip Hover
4.3.4 Thefirst child pseudo classes
4.3.5Matchthe first<p>element
workingwithPseudo-elements
The:first-linepseudo-element
The:first-letterpseudo-element
The:beforepseudo-element
The:afterpseudo-element
The:selectionpseudo-element
Creatinganavigationbar
NavigationBar=ListofLinks
4.11.2Vertical navigation bar
CenterLinks &Add Borders
HorizontalNavigationBar
Workingwith images
TheImageBorderProperty
TheImagewidthProperty
WorkingwithAttributeselectors
4.13.1Multiple style rules
CSS[attribute]Selector
CSS[attribute="value"] Selector
CSS[attribute~="value"] Selector
CSS[attribute|="value"]Selector
CSS[attribute^="value"] Selector
CSS[attribute $="value"] Selector
CSS[attribute*="value"] Selector
CheckYourProgressPossible answer
Reference
Paddingusing CSS
The padding property allows you to specify how much space should appear between
the content of an element and its border: The value of this attributeshould be either
a length, a percentage, or the word inherits. If the value is inherit, it will have the
same padding as its parent element. If a percentage is used, the percentage is of the
containing box. The following CSS properties can be used to control lists. You can
also set different values for the padding on each side of the box using the following
properties:
Thepadding-bottom specifiesthebottom paddingofan element.
Thepadding-top specifiesthe top paddingofan element.
Thepadding-leftspecifies theleftpaddingofanelement.
Thepadding-right specifiestherightpaddingofanelement.
Thepaddingserves as shorthand forthe preceding properties.
Thepadding-bottom Property
The padding-bottom property sets the bottom padding (space) of an element. This
can take a value in terms of length of %. Here is an example:
Theaboveprogramwillproducethe followingresult
Thepadding-topProperty
Thepadding-toppropertysetsthetoppadding(space)ofanelement.Thiscantakea value
in terms of length of %. Here is an example:
Theaboveprogramwillproducethe followingresult:
OdishaStateOpenUniversity Page72
SettingDisplayUsingCSS
Thedisplayproperty is the most important CSS property for controlling layout.
Thedisplayproperty specifies if/how an element is displayed. Every HTML element
has a default display value depending on what type of element it is. The
defaultdisplayvalueformostelementsis blockorinline.Ablockelementis often called
a block-level element. An inline element is always just called aninline element.
Block-levelElements
Ablock-levelelementalwaysstartsonanewlineandtakesupthefullwidth available
(stretches out to the left and right as far as it can).
The<div>elementisablock-levelelement.
Examplesofblock-levelelements:
<div>
<h1>-<h6>
<p>
<form>
<header>
<footer>
<section>
<div>
divis the standard block-level element. A block-level elementstarts
on anewlineand stretches out to theleft and right as faras it can.Other
commonblock-levelelementsarepandform,andnew in HTML5 are
header, footer, section, and more.
</div>
InlineElements
An inline element doesnot starton a new line and only
takesupasmuchwidthasnecessary. Thisisaninline<span>
elementinsideaparagraph.
Spanis the standard inline element. An inline element can wrap
sometextinsideaparagraph <span>likethis</span>without disrupting
the flow of that paragraph. The a element is the most common inline
element, since you use them for links.
Examplesof inlineelements:
<span>
<a>
<img>
Page73
CSSSyntax
Display:value;
This<div>elementhasawidthof500px,andmarginsetto auto.
Note: The problem with the<div>above occurs when the browser window is
smaller than the width of the element. The browser then adds a horizontalscrollbar
to the page.
This<div>elementhasamax-widthof500px,andmargin set
to auto.
Page74
Hereis anexampleofthetwo divs above:
Page75
Theoutputoftheaboveprogramisfollowingbellow:
SettingPositionusingCSS
CSS helps you to position your HTML element. You can put any HTML element
at whatever location you like. You can specify whether you want the element
positioned relative to its natural position in the page or absolute based on itsparent
element. Now, we will see all the CSS positioning related properties with examples.
Relative Positioning
Relative positioning changes the position of the HTML element relative to where it
normally appears. So "left:20" adds 20 pixels to the element's LEFT position. You
can use two values top and left along with the position property to move an HTML
element anywhere in an HTML document.
MoveLeft-Useanegativevaluefor left.
MoveRight-Useapositivevalueforleft.
MoveUp-Use anegativevalue for top.
MoveDown-Useapositivevalue fortop.
NOTE:Youcanusethebottomorrightvaluesaswellinthesamewayastopand left.
Page76
Hereisanexample:
Theaboveprogramwillproducethe followingresult:
AbsolutePositioning
MoveLeft-Useanegativevaluefor left.
MoveRight-Useapositivevalueforleft.
MoveUp-Use anegativevalue for top.
MoveDown-Useapositivevalue fortop.
Page77
</div>
FixedPositioning
Fixed positioning allows you to fix the position of an element to a particular spot
on the page, regardless of scrolling. Specified coordinates will be relative to the
browser window.You can use two values top and left along with the position
property to move an HTML element anywhere in the HTML document.
MoveLeft-Useanegativevaluefor left.
MoveRight-Useapositivevalueforleft.
MoveUp-Use anegativevalue for top.
MoveDown-Useapositivevalue fortop.
NOTE:Youcanusebottomorrightvaluesaswellinthesamewayastopand left.
Hereisanexample:
Settingthefloatpropertyusing CSS
A float is a box that is shifted to the left or right on the current line. The most
interesting characteristic of a float (or "floated" or "floating" box) is that content
may flow along its side (or be prohibited from doing so by the property).
WithCSSfloat,anelementcanbepushedtotheleftorright,allowingother
elementstowrap aroundit.Floatisveryoftenusedforimages,butitisalso useful
when working with layouts.
A line box is next to a float when there exists a vertical position that satisfies
allof these four conditions:
(a) Ator below the topofthe line box,
(b) Atorabovethe bottom of theline box
(c) Belowthetopmarginedgeofthefloat, and
(d) Abovethe bottom marginedgeof the float.
Elements Float
Elements are floated horizontally; this means that an element can only be
floated left or right, not up or down. A floated element will move as far to the left
or right as it can. Usually this means all the way to the left or right of the containing
element. The elements after the floating element will flow around it. The elements
before the floating element will not be affected. If an image is floated to the right,
a following text flows around it, to the left:
Page78
Example:
img{float:right;}
If youplaceseveralfloatingelementsaftereachother,theywillfloatnexttoeach other if
there is room.Here we have made an image gallery using the float property:
Example
.thumbnail{float:left;width:110px;height:90px;margin:5px;}
TurningoffFloat-UsingClear
Elements after the floating element will flow around it. To avoid this, use
the clear property. The clear property specifies which sides of an element
other floating elements are not allowed.Add a text line into the image
gallery, using the clear property:
Example:
.text_line{clear:both;}
AllCSSFloatProperties
Thenumberinthe"CSS"columnindicatesinwhichCSSversionthe property is
defined (CSS1 or CSS2).
Theaboveprogramwillproducethe followingresult:
Page79
Page80
Checkyourprogress1
Q1.Whatis Float ?
Answer:
Q2.Writethedifferentpropertiesof position?
Answer:
Q3.Whatis padding?
Answer:
Q4.WritetheuseofDisplay properties?
Answer:
InlineBlock Properties
It has been possible for a long time to create a grid of boxes that fills the
browserwidthandwrapsnicely(whenthebrowserisresized),byusing thefloatproperty.
However, theinline-blockvalue of thedisplayproperty makes this even easier.
Inline-block elements arelike inline elements but theycan have a width and a height.
Examples
Theoldway-usingfloat (noticethatwealsoneed tospecifyaclearpropertyfor the
element after the floating boxes):
<!DOCTYPEhtml>
<html>
<head>
<style>
.floating-box
{
float: left;
width: 150px;
height: 75px;
margin: 10px;
border:3px solid #73AD21;
}
.after-box
Page81
{
clear:left;
border:3px solid red;
}
Page82
</style>
</head>
<body>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="floating-box">Floatingbox</div>
<divclass="after-box">Anotherbox,afterthefloatingboxes...</div>
</body>
</html>
Theaboveprogramwillproducethe followingresult
HorizontalAlignmentinCSS
InCSS,severalpropertiescanbeusedtoalignelementshorizontallyand vertically.
Page83
Example:
.center
{
margin:auto;
width: 50%;
border:3pxsolidgreen; padding:
10px;
}
Note:Centeraligninghasnoeffectifthewidthpropertyisnotset(orsetto 100%).
Tojustcenterthetextinsideanelement,usetext-align:center; Example:
.center
{
text-align: center;
border:3pxsolidgreen;
}
CenteranImage
Tocenteranimage,usemargin:auto;andmakeitintoablockelement:
img
{
display:block;
margin: auto;
width: 40%;
}
Example:
.right{
position:absolute;
right: 0px;
width:300px;
border:3pxsolid#73AD21;
padding: 10px;
}
Page84
Tip:When aligningelements withposition,always definemarginandpaddingfor
the<body>element. This is to avoid visual differences in different browsers. There
is also a problem with IE8 and earlier, when using position. If a container
element(inourcase<divclass="container">)hasaspecifiedwidth,andthe
!DOCTYPE declaration is missing, IE8 and earlier versions will add a 17px margin
on the right side. This seems to be space reserved for a scrollbar. So, always set the
!DOCTYPE declaration when using position:
<!DOCTYPEhtml>
<html>
<head>
<style>
body
{
margin: 0;
padding:0;
}
.container
{
position:relative;
width: 100%;
}
.right
{
position:absolute;
right: 0px;
width: 300px;
background-color:#b0e0e6;
}
</style>
</head>
<body>
<h2>RightAlign</h2>
<divclass="container">
<divclass="right">
<p><b>Note:</b>Whenaligningusingthepositionproperty,
always include the !DOCTYPE declaration! If missing, it can
produce strange results in IE browsers.</p>
</div>
</div>
</body>
</html>
Theaboveprogramwillproducethe followingresult
Page85
Workingwith Combinatory
A combinatory is something that explains the relationship between the selectors.A
CSS selector can contain more than one simple selector. Between the simple
selectors, we can include a combinatory.
Therearefourdifferentcombinatoryin CSS:
descendantselector(space)
childselector(>)
adjacentsiblingselector (+)
generalsiblingselector(~)
Descendant Selector
Thedescendantselectormatchesallelementsthataredescendantsofa specified
element.
Thefollowingexampleselectsall<p>elementsinside<div>elements:
Example
div p
{
background-color:yellow;
}
Page86
ChildSelector
Thechildselectorselectsallelementsthataretheimmediatechildrenofa
specified element.
Thefollowingexampleselectsall<p>elementsthatareimmediate children of
a <div> element:
Example
<div> p{
background-color:yellow;
}
AdjacentSiblingSelector
The adjacent sibling selector selects all elements that are the adjacent
siblings of a specified element. Sibling elements must have the sameparent
element, and "adjacent" means "immediately following". The following
example selects all <p> elements that are placed immediately after <div>
elements:
Example:
div + p{
background-color:yellow;
}
General SiblingSelector
The general sibling selector selects all elements that are siblings of a
specifiedelement. Thefollowingexampleselectsall <p>elements that are
siblings of <div> elements:
Example:
div ~ p {
background-color:yellow;
}
WorkingwithPseudo-class
Apseudo-classisusedtodefineaspecialstateofanelement. Forexample,it can be
used to:
Styleanelementwhena usermousesoverit
Stylevisitedandunvisitedlinksdifferently
Styleanelementwhenit getsfocus
Syntax
Thesyntaxofpseudo-classes:
selector: pseudo-class
Page87
{
property:value;
}
AnchorPseudo-classes
Linkscanbedisplayedindifferentways:
Example
/*unvisitedlink*/ a:link
{
color:#FF0000;
}
/*visitedlink*/
a:visited {
color:#00FF00;
}
/*mouseoverlink*/
a:hover {
color:#FF00FF;
}
/*selectedlink*/
a:active {
color:#0000FF;
}
Note:a:hoverMUSTcomeaftera:linkanda:visitedintheCSS
definitioninordertobe effective!a:active MUST comeafter a:hoverinthe CSS
definition in order to be effective! Pseudo-class names are not case-
sensitive.
Pseudo-classesandCSS Classes
Pseudo-classescanbecombinedwithCSSclasses:Whenyouhoverover the
link in the example, it will change color:
Example
a.highlight:hover
{
color:#ff0000;
}
Hoveron<div>
Anexample ofusingthe:hoverpseudo-class ona<div>element:
Example
div:hover
{
background-color:blue;
}
SimpleTooltipHover
Hoverovera<div>elementtoshowa<p>element(likeatooltip): Hover
over me to show the <p> element.
Example
Page88
p
{
display:none;
background-color:yellow;
padding: 20px;
}
div:hoverp
{
display:block;
}
The:first-childPseudo-class
The: first-childpseudo-class matchesa specifiedelement that is the first
child of another element.
Matchthefirst<p>element
Inthefollowingexample,theselectormatchesany<p>elementthatisthe first
child of any element:
Example
p:first-child
{
color:blue;
}
Example
pi:first-child
{
color:blue;
}
Page89
:empty p:empty Selectsevery<p>elementthat
has no children
Page90
p:nth-of- Selectsevery<p>elementthati
:nth-of-type(n) type(2) s the second <p> element of
its parent
"required"attribute
WorkingwithPseudo-elements
CSS pseudo-elements are used to add special effects to some selectors. You do
notneedtouseJavaScriptoranyotherscripttousethoseeffects.Asimplesyntax of
pseudo-element is as follows:
selector:pseudo-element{property: value}
CSSclassescanalso be usedwiththepseudo-elements:
selector.class:pseudo-element{property: value}
Page91
Themost commonlyused pseudo-elements are as follows:
Value Description
:first-line Usethiselement toadd specialstyles tothefirst
lineof thetext in a selector.
:first- Usethis elementto addspecial styleto thefirst
letter letterof thetext in a selector.
:before Usethiselementto insertsomecontentbeforean
element.
:after Usethiselementto insertsomecontentafter an
element.
Page92
The:first-linepseudo-element
Thefollowingexampledemonstrateshowtousethe:first-lineelementtoadd special
effects to the first line of elements in a document.
Theaboveprogramwillproducethe followingresult :
The:first-letterpseudo-element
Thefollowingexampledemonstrateshowtousethe:first-letterelementtoaddspecial
effect to the first letter of elements in the document.
Page93
Theaboveprogramwillproducethe followingresult:
Page94
The:beforepseudo-element
<styletype="text/css">
p:before
{
content:url(/https/www.scribd.com/images/bullet.gif)
}
</style>
<p>This line will bepreceded byabullet.</p>
<p>This line will bepreceded byabullet.</p>
<p>This line will bepreceded byabullet.</p>
The:afterpseudo-element
<styletype="text/css">
p:after
{
content:url(/https/www.scribd.com/images/bullet.gif)
}
</style>
<p>This line will be succeeded byabullet.</p>
<p>This line will be succeeded byabullet.</p>
<p>This line will be succeeded byabullet.</p>
The::selectionPseudo-element
The:selectionpseudo-elementmatchestheportionofanelementthatisselected by a
user. The following CSS properties can be applied to:
selection:color,background,cursor,andoutline.Thefollowingexamplemakes the
selected text red on a yellow background: Here is an example:
<!DOCTYPEhtml>
<html>
<head>
<style>
::-moz-selection{/*CodeforFirefox*/
color: red;
background:yellow;
Page95
}
::selection {
color:red;
background:yellow;
}
</style>
</head>
<body>
<h1>Selectsometextonthispage:</h1>
<p>Thisisa paragraph.</p>
<div>Thisissometextinadivelement.</div>
<p><strong>Note:</strong>::selectionisnotsupportedinInternet
Explorer 8 and earlier versions.</p>
<p><strong>Note:</strong>Firefoxsupportsanalternative,the::-
moz- selection property.</p>
</body>
</html>
Theaboveprogramwillproducethe followingresult:
Page96
Creatinganavigationbar
Anavigation bar(ornavigationsystem) is a section of a graphical user
interface intended to aid visitors in accessing information. Navigation barsare
implemented in file browsers, web browsers and as a design element of some web
sites. A set of buttons or images in a row or column that serves as a control point to
link the user to sections on a Web site. The navigationbarmay also be asingle
graphic image with multiple selections.
(Exampleofverticalandhorizontalnavigationbar)
Nowlet'sremovethebulletsandthemarginsandpaddingfromthelist: ul
{
list-style-type:none;
margin:0;padding:0;
}
Page97
Exampleexplained:
list-style-type:none-Removesthebullets.Anavigationbardoesnotneed list
markers
Settingmarginsandpaddingto 0toremovebrowserdefault settings
Thecodeintheexampleaboveisthestandardcodeusedinbothvertical,and horizontal
navigation bars.
VerticalNavigationBar
Tobuildaverticalnavigationbarweonlyneedtostylethe<a>elements,in addition to
the code above:
Example
a{display:block;width:60px;}
Example explained:
display:block-Displayingthelinksasblockelementsmakesthewhole link area
clickable (not just the text), and it allows us to specify the width
width:60px - Block elements take up the full width available by
default.We want to specify a 60 px width .
Note: Always specify the width for <a> elements in a vertical navigation bar. If you
omit the width, IE6 can produce unexpected results. You can also set the width of
<ul>, and remove the width of <a>, as they will take up the full width available
when displayed as block elements. This will produce the same result as our previous
example:
ul {
list-style-type:none;
margin: 0;
padding: 0;
width:60px;
}
li a{
display:block;
}
CenterLinks&Add Borders
<!DOCTYPEhtml>
<html>
<head>
<style>
ul {
list-style-type:none;
margin: 0;
Page98
padding: 0;
width:200px;
background-color:#f1f1f1;
border: 1px solid #555;
}
li a{
display: block;
color: #000;
padding:8px16px;
text-decoration:none;
}
li {
text-align:center;
border-bottom:1pxsolid#555;
}
li:last-child{
border-bottom: none;
}
lia.active{
background-color:#4CAF50;
color: white;
}
li a:hover:not(.active) {
background-color:#555;
color: white;
}
</style>
</head>
<body>
<h2>VerticalNavigation Bar</h2>
<p>Inthisexample,wecenterthenavigationlinksandaddabordertothe
navigation bar.</p>
<ul>
<li><aclass="active"href="#home">Home</a></li>
<li><ahref="#news">News</a></li>
<li><ahref="#contact">Contact</a></li>
<li><ahref="#about">About</a></li>
</ul>
</body>
</html>
Page99
Theaboveprogramwillproducethe followingresult
HorizontalNavigation Bar
There are two ways to create a horizontal navigation bar. Using inline or
floating list items.Both methods work fine, but if you want the links to be the same
size, you have to use the floating method. Create a basic horizontal navigation bar
with a dark background color and change the background color of the links when
the user moves the mouse over them:
<!DOCTYPEhtml>
<html>
<head>
<style>
ul {
list-style-type:none;
margin: 0;
padding: 0;
overflow:hidden;
background-color:#333;
}
li {
Page100
float:left;
}
li a{
display:block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration:none;
}
lia:hover{
background-color:#111;
}
</style>
</head>
<body>
<ul>
<li><aclass="active"href="#home">Home</a></li>
<li><ahref="#news">News</a></li>
<li><ahref="#contact">Contact</a></li>
<li><ahref="#about">About</a></li>
</ul>
</body>
</html>
Page101
Workingwith images
TheImageBorderProperty
Theborderpropertyofanimageisusedtosetthewidthofanimageborder.This property
can have a value in length or in %.A width of zero pixels means no border.
Hereisanexample:
Page102
Theaboveprogramwillproducethe followingresult:
TheImageWidth Property
Thewidth propertyofan imageis used to set the width ofan image. This property can
have avaluein length orin %. Whilegivingvaluein %, it applies it in respect of the
box in which an image is available.
Page103
Hereisanexample:
Page104
Theaboveprogramwillproducethe followingresult:
Page105
Working with attribute selectors
You can also apply styles to HTML elements with particular attributes. The style
rulebelowwillmatchall theinputelementshavingatypeattributewithavalueof text:
input[type="text"]
{
color:#000000;
}
Theadvantagetothismethodisthatthe<inputtype="submit"/>elementis unaffected,
and the color applied only to the desired text fields.
Therearefollowingrulesappliedtoattributeselector.
CSS[attribute]Selector
The[attribute]selectorisusedtoselectelementswithaspecifiedattribute.The
following example selects all <a> elements with a target attribute:
Example
a[target]{
background-color:yellow;
}
Page106
CSS[attribute="value"]Selector
a[target="_blank"] {
background-color:yellow;
}
CSS[attribute~="value"]Selector
The[attribute~="value"]selectorisusedtoselectelementswithanattributevalue
containing a specified word. The following example selects all elements with a
title attribute that contains a space-separated list of words, one of which is
"flower":
Example
[title~="flower"]{
border:5pxsolidyellow;
}
The example above will match elements with title="flower", title="summer
flower",andtitle="flowernew",butnottitle="my-flower"ortitle="flowers".
CSS [attribute|="value"]Selector
CSS [attribute^="value"]Selector
The[attribute^="value"]selectorisusedtoselectelementswhoseattributevalue begins
with a specified value.
Thefollowingexampleselectsallelementswithaclassattributevaluethatbegins with
"top":
Note:Thevaluedoes not haveto bea wholeword!
Example
[class^="top"] {
background:yellow;
}
Page107
CSS[attribute$="value"]Selector
The[attribute$="value"]selectorisusedtoselectelementswhoseattributevalue ends
with a specified value.
Thefollowingexampleselectsallelementswithaclassattributevaluethatends with
"test":
Note:Thevaluedoes not haveto bea wholeword!
Example
[class$="test"] {
background:yellow;
}
CSS[attribute*="value"]Selector
[class*="te"] {
background:yellow;
}
Checkyourprogress2
Q1.Writethedifferentpropertiesof image?
Answer:
Q2.WhatisPseudoClass ?
Answer:
Answer:
Page108
Letus sumup
In this unit we have understood padding using CSS,setting
displayusingCSS,settingwidthandmaxwidthusingCSS,settingfloatproper
CSS,working
withcombinatory,pseudo-class,pseudo-elements,creatinganavigationbar, working
Reference
1. W3Schools.com
2. Google.com
3. Tutorialpoints.com
CheckYourProgressPossibleanswer
Check your progress 1
Q1.WhatisFloat?
Answer
A float is a box that is shifted to the left or right on the current line. The most
interestingcharacteristicofafloat(or"floated"or"floating"box)isthatcontentmay flow
along its side (or be prohibited from doing so by the property).
Q2.Writethedifferentpropertiesofposition?
Answer
Positionpropertyto movean HTMLelement anywherein anHTMLdocument.
MoveLeft-Useanegativevaluefor left.
MoveRight-Useapositivevalueforleft.
MoveUp-Use anegativevalue for top.
MoveDown-Useapositivevalue fortop.
Q3.Whatispadding? Answer
Thepaddingpropertyallowsyoutospecifyhowmuchspaceshouldappearbetween the
content of an element and its border
Q4.WritetheuseofDisplayproperties? Answer
ThedisplaypropertyisthemostimportantCSSpropertyforcontrollinglayout. The
display property specifies if/how an element is displayed
Page109
Checkyourprogress2
Q1.Writethedifferentpropertiesof image?
Q2.WhatisPseudoClass? Answer
Q3.Whatisnavigationbar? Answer
What is xml
Students often underline or highlight a passage to revise easily, same in the sense of modern mark up
language highlighting or underlining is replaced by tags.
Prerequisite
Before you start to learn xml, you should know basic of HTML & JavaScript.
Why xml
Platform Independent and Language Independent: The main benefit of xml is that you can use it to
take data from a program like Microsoft SQL, convert it into XML then share that XML with other
programs and platforms. You can communicate between two platforms which are generally very
difficult.
With XML, data can be stored in separate XML files. This way you can focus on using HTML/CSS for
display and layout, and be sure that changes in the underlying data will not require any changes to the
HTML.
With a few lines of JavaScript code, you can read an external XML file and update the data content of
your web page.
XML data is stored in plain text format. This provides a software- and hardware-independent way of
storing data.
This makes it much easier to create data that can be shared by different applications.
Exchanging data as XML greatly reduces this complexity, since the data can be read by different
incompatible applications.
XML data is stored in text format. This makes it easier to expand or upgrade to new operating systems,
new applications, or new browsers, without losing data.
With XML, your data can be available to all kinds of "reading machines" (Handheld computers, voice
machines, news feeds, etc), and make it more available for blind people, or people with other disabilities.
o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web
2
XML Example
XML documents create a hierarchical structure looks like a tree so it is known as XML Tree that starts
at "the root" and branches to "the leaves".
3
WMV .wmv WMV (Windows Media Video). Developed by
Microsoft. Commonly used in video cameras
and TV hardware. Plays well on Windows
computers, but not in web browsers.
4
Practiced questions :
Cascading Style Sheets (CSS)
1. What is CSS?
2. What are the main purposes of using CSS in web development?
3. Explain the advantages of CSS over inline styling.
4. What are the different ways to add CSS to a web page?
5. How does an external CSS file improve the maintainability of a website?
6. Write an example of inline, internal, and external CSS.
7. What is the difference between inline, internal, and external CSS?
8. How does CSS improve page loading speed?
9. What do you mean by the "Cascading" nature of CSS?
10. What are the different types of CSS selectors? Provide examples.
11. What is the importance of the <link> tag in CSS?
12. How can you apply the same style to multiple elements in CSS?
13. What is the role of the class and id selectors in CSS?
14. How do you group multiple selectors in CSS? Provide an example.
15. What is the difference between id and class selectors in CSS?
16. Explain the concept of inheritance and specificity in CSS.
17. What is a CSS box model?
18. What are pseudo-classes and pseudo-elements in CSS?
19. How can CSS be used to create responsive web pages?
20. What are media queries in CSS?
Extensible Markup Language (XML)
21. What is XML?
22. How is XML different from HTML?
23. What are the main features of XML?
24. Explain the structure of an XML document with an example.
25. What are XML tags? How are they different from HTML tags?
26. What is an XML schema (XSD)?
27. How does XML help in data storage and exchange?
28. What are well-formed and valid XML documents?
29. What is the role of a Document Type Definition (DTD) in XML?
30. What is the difference between XML Schema and DTD?
31. How is XML used in web development?
32. Explain the concept of namespaces in XML.
33. What is an XML parser?
34. How does XML interact with databases?
35. What are the advantages of using XML for data representation?
36. How is XML used in web services (SOAP & REST)?
37. What are CDATA sections in XML?
38. What is XSLT in XML, and why is it used?
39. What are the common applications of XML?
40. Explain the difference between JSON and XML.