0% found this document useful (0 votes)
22 views114 pages

WD 3

The document provides study material for a Web Designing course focusing on XML and DHTML, covering concepts such as Cascading Style Sheets (CSS) and their application in creating dynamic web pages. It explains the components of DHTML, its uses, features, and differences from HTML, along with examples of JavaScript integration for dynamic content. Additionally, it introduces CSS, its advantages, and the syntax for applying styles to HTML elements.

Uploaded by

kowsalya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views114 pages

WD 3

The document provides study material for a Web Designing course focusing on XML and DHTML, covering concepts such as Cascading Style Sheets (CSS) and their application in creating dynamic web pages. It explains the components of DHTML, its uses, features, and differences from HTML, along with examples of JavaScript integration for dynamic content. Additionally, it introduces CSS, its advantages, and the syntax for applying styles to HTML elements.

Uploaded by

kowsalya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

MARUDHAR KESARI JAIN COLLEGE FOR WOMEN

(AUTONOMOUS)
VANIYAMBADI
PG and Department of Computer Science

3nd BSC CS

Semester- VI

E Notes(StudyMaterial)

Foundation Course -1: Web Designing Code:23USCS43

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.

Components of Dynamic HTML


DHTML consists of the following four components or languages:
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
HTML is a client-side markup language, which is a core component of the DHTML. It defines the
structure of a web page with various defined basic elements or tags.

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:

1. DHTML is not a language, but it is a set of


1. HTML is simply a markup language.
technologies of web development.
2. It is used for developing and creating web 2. It is used for creating and designing the
pages. animated and interactive web sites or pages.

3. This markup language creates static web


3. This concept creates dynamic web pages.
pages.

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.

JavaScript and HTML DOM


With version 4 of HTML, JavaScript code can also change the inner content and attributes of the
HTML event.

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.

CSS with JavaScript in DHTML


With version 4 of HTML, JavaScript code can also change the style such as size, color, and face
of an HTML element.

Example 1: The following example changes the color of a text.

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:

In the above code, we used the var element = document.getElementById('demo').style.color =


newColor; statement, which changes the color of a text as green and blue according to the buttons.

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

Cascading Style Sheets(CSS) is a simple mechanism used to format the


layout of Web Pages and addingstyle(e.g., fonts, colors, spacing...) to web
documentsthatpreviouslycouldonlybedefinedinapage'sHTML. CSSdescribes how
HTML elements are to be displayed on screen, paper, or in other media. It can
control the layout of multiple web pages all at once.

Advantages

Theadvantages ofCSS are:


 CSSsavestime-YoucanwriteCSSonceandthenreusethesamesheet in
multiple HTML pages.
 Pagesloadfaster–IncreasesDownloadSpeed
 Easymaintenance-Tomakeaglobalchange,alltheelementsinallthe web
pages will be updated automatically.
 SuperiorstylestoHTML–Itisbetterlookto yourHTMLpagein
comparison to HTML attributes.
 MultipleDeviceCompatibility-Stylesheetsallowcontenttobe
optimized for more than one type of device.
 Globalwebstandards-NowHTMLattributesarebeingdeprecatedand it is
being recommended to use CSS

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

ACSSstyleruleismade ofthree parts:


1. Selector:AselectorisanHTMLtagatwhichastylewillbeapplied.This could
be any tag like <h1>, <p> or <table> etc.
2. Property:ApropertyisatypeofattributeofHTMLtag.Putsimply,all the
HTML attributes are converted into CSS properties. They could be
color, border, bgcolor etc.
3. Value:Valuesareassignedtoproperties.Forexample,colorpropertycan have
the value either red or #F1F1F1 etc.

Theformat orsyntaxof CSS is:

Selector{property:

Example:Youcandefineaheadingasfollows:

h1 {color:red;font-size:15px}

Selector Property Value Property Value

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

Youcandefineselectorsinvarioussimplewaysbasedon yourcomfort.Letme put these


selectors one by one. Three types of CSS Selectors
1. TheElementselectors
2. TheID Selectors
3. TheClass Selectors
TheElementselectors
A CSS declaration always ends with a semicolon, and declaration groups
are surrounded by curly brackets: example -
p{color:red;text-align:center;}
TomaketheCSSmorereadable, youcanputonedeclarationoneachline, like
this:
p
{
color:red;
text-align:center;
}
TheID selectors

The id selector is used to specify a style for a single, unique


element.TheidselectorusestheidattributeoftheHTMLelement,andisdefined
witha "#". Example –
Imaginewithinthebodyelementofourhtmlpage,wehavethefollowing
paragraph element
<pid=”welcome”>Welcometothe1stCSS Document </p>
Wecan thencreateaCSSrule withthe id selector:

#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

Q1.Whatarethe 3types ofselectors?.


Answer:

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

Q1.Howmanyways tobuildstylesheet ?whatarethey ?


Answer:

Q2.Writethe backgroundpropertiesofCSS.

Answer:

BackgroundcolourManagementusingCSS

Thebackground-colorpropertyspecifiesthebackgroundcolorofan element. The


background color of a page is defined in the bodyselector: Example

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.

CSS Colors-ShortHex Codes


This is a shorter form of the six-digit notation. In this format, each digit is
replicatedtoarriveatanequivalentsix-digitvalue.Forexample:#6A7becomes
#66AA77.
CSS Colors-RGBValues

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

CSSisalanguagethatdescribesthestyleofanHTMLdocument. Youcansetthe following


text properties of an element:

 Thecolorpropertyis used toset thecolor ofa text.


 Thedirectionpropertyis used to set thetext direction.
 The letter-spacing property is used to add or subtract space between
theletters that make up a word.
 The word-spacing property is used to add or subtract space between
thewords of a sentence.
 Thetext-indentpropertyis used to indent thetextof a paragraph.
 Thetext-alignpropertyis used to align the text of a document.
 Thetext-decorationpropertyisusedtounderline,overline,and strikethrough
text.
 Thetext-transform property isusedtocapitalizetextorconverttextto
uppercase or lowercase letters.
 Thewhite-spacepropertyisusedtocontroltheflowandformattingof text.
 Thetext-shadowpropertyis usedto set the textshadowaround atext.

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

The following example demonstrates how to set the space between


characters.Possiblevaluesarenormaloranumberspecifyingspace.

<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

Thefollowingexampledemonstrateshowtodecorateatext.Possible values are


none, underline, overline, line-through, blink.

<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:

 Thefont-familypropertyisused tochangethefaceofa font.


 Thefont-stylepropertyis used tomakeafontitalic oroblique.
 Thefont-variantpropertyisused to create asmall-caps effect.
 Thefont-weightpropertyisusedtoincreaseordecreasehowboldorlight a font
appears.
 Thefont-sizepropertyisusedto increaseor decreasethe sizeof a font.
 Thefontpropertyisusedasshorthandtospecifyanumberofotherfont
properties.

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 %.

<pstyle="font-size:20px;">This fontsizeis 20pixels </p>


<pstyle="font-size:small;">Thisfontsizeissmall</p>
<pstyle="font-size:large;">Thisfontsizeislarge</p>

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

The following example demonstrates how to set the font stretch of


an element. This property relies on the user's computer to have an
expanded or condensed version of the font being used.
Possible values could be normal, wider, narrower, ultra-condensed,
extra-condensed, condensed, semi-condensed, semi-expanded,
expanded, extra-expanded, ultra-expanded.
<pstyle="font-stretch:ultra-expanded;">
If this doesn't appear to work, it is likely thatyour computer
doesn'thaveacondensedorexpandedversionofthefontbeing used.
</p>
Example:-

Theoutputof theaboveprogramis :
ManaginghyperlinksusingCSS

An element in an electronic document that links to another place in the same


document or to an entirely different document. A hyperlink, or simplyalink, is a
reference to data that the reader can directly follow either by clicking, tapping, or
hovering. Ahyperlinkpoints to a whole document or to a specific element within a
document. Hypertext is text with hyperlinks. The text that is linked is called anchor
text. You can set the following properties of a hyperlink:

 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>

SettheColorof Visited Links

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

Q1.Whatistherepresentationof 6digit Hexacode?


Answer:

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

Herearethevalues,whichcan beused for anordered list:

Value Description Example


Decimal Number 1,2,3,4…..
decimal- 0beforethenumber 01, 02,
leading- …..
zero
lower- Lowercasealphanumeric a,b,c, ….
alpha characters
upper- Uppercasealphanumeric A,B,C,
alpha characters D, E..
lower- LowercaseRoman i, ii, iii, iv,
roman numerals v
upper- UppercaseRoman I,II,III,
roman numerals IV,V

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

Tables are an excellent way to organize and display information on a page.


Youcan set the following properties of a table:

 The border-collapse specifies whether the browser should control the


appearance of the adjacent borders that touch each other or whether each
cell should maintain its style.
 The border-spacing specifies the width that should appear between table
cells.
 The caption-side captions are presented in the <caption> element. By
default, these are rendered above the table in the document. You use the
caption-side property to control the placement of the table caption.
 The empty-cells specify whether the border should be shown if a cell is
empty.
 The table-layout allows browsers to speed up the layout of a table by using
the first width properties it comes across for the rest of a column rather than
having to load the whole table before rendering it.

Theorder-collapse Property

Thisproperty canhavetwovaluescollapse andseparate. The following


example uses both the values:

<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

The border-spacing property specifies the distance that separates the


adjacent cells’ borders. It can take either one or two values; these should be units
of length. If you provide one value, it applies to both vertical and horizontal borders.
Or you can specify two values, in which case, the first refers to the horizontal
spacing and the second to the vertical spacing:
NOTE: Unfortunately, this propertydoes not work in Netscape 7 or IE 6.
Now let's modify the previous example and see the effect:
<styletype="text/css">t
able.one
{
border-collapse:separate;width:400px;
border-spacing:10px;
}
table.two
{
border-collapse:separate;width:400px;
border-spacing:10px 50px;
}
</style>
<tableclass="one" border="1">
<caption>SeparateBorderExamplewithborder-spacing</caption>
<tr><td>CellACollapse Example</td></tr>
<tr><td>CellBCollapse Example</td></tr>
</table><br/>
<tableclass="two" border="1">
<caption>SeparateBorderExamplewithborder-spacing</caption>
<tr><td>CellASeparate Example</td></tr>
<tr><td>CellBSeparate Example</td></tr>
</table>

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

Q1.Whatisthedifferent propertiesof tableincss ?


Answer:

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:

Theoutputof theabove program is:


Theline-height Property

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:

Theoutput oftheabove program is

Themax-height Property

Themax-height propertyallows you to specifythe maximum height of a box. The


value of the max-height property can be a number, a length, or a percentage.

NOTE:ThispropertydoesnotworkineitherNetscape7or IE6. Here is an


example:
Theoutputof theabove program is

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

Designingborders using CSS

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

Theborder-stylepropertyallows youtoselectoneofthefollowingstylesof border:


 none:Noborder.(Equivalentofborder-width:0;)
 solid:Border is asinglesolid line.
 dotted:Borderisaseriesof dots.
 dashed:Borderis aseries ofshort lines.
 double:Borderistwosolidlines.
 groove:Borderlooksasthough itiscarvedintothe page.
 ridge:Border looks theopposite of groove.
 inset:Bordermakesthe boxlooklikeitisembeddedinthepage.
 outset:Bordermakesthe boxlooklike itiscomingoutofthecanvas.
 hidden:Sameasnone,exceptintermsofborder-conflictresolutionfortable
elements.

Youcanindividuallychangethestyleofthebottom,left,top,andrightbordersof an
element using the following properties:

 border-bottom-stylechangesthestyleofbottomborder.
 border-top-stylechangesthestyleoftopborder.
 border-left-stylechangesthestyleofleftborder.
 border-right-stylechangesthestyleofrightborder.

Thefollowingexampleshowsall theseborder styles:

Itwillproducethefollowingresult:
DesigningoutlineusingCSS

Outlinesareverysimilar toborders,but there arefew majordifferencesaswell:


 Anoutlinedoes not take up space.
 Outlinesdo not haveto be rectangular.
 Outlineisalwaysthesameonallsides;youcannotspecifydifferentvalues for
different sides of an element.

NOTE:The outline properties are not supported byIE 6 or Netscape 7. You can
set the following outline properties using CSS.

 Theoutline-width propertyis used toset thewidthof the outline.


 Theoutline-stylepropertyisused tosetthelinestyleforthe outline.
 Theoutline-color propertyis used toset thecolorofthe outline.
 Theoutlinepropertyisusedtosetalltheabovethreepropertiesinasingle
statement.

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

The margin property defines the space around an HTML element. It is


possible to use negative values to overlap content. The values of the margin
property are not inherited by the child elements. Remember that the adjacent
vertical margins (top and bottom margins) will collapse into each other so that the
distance between the blocks is not the sum of the margins, but only the greater of
the two margins or the same size as one margin if both are equal.
Wehavethe followingpropertiesto set an element margin.
 Themarginspecifiesashorthandpropertyforsettingthemargin
properties in one declaration.
 Themargin-bottomspecifiesthebottommarginofanelement.
 Themargin-topspecifiesthetopmarginof anelement.
 Themargin-leftspecifiestheleftmarginofanelement.
 Themargin-rightspecifiestherightmarginofanelement.

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

p{margin: 10px2%-10px auto}


top margin will be 10px, right margin will be 2% of the total width of the
document,bottommarginwillbe-10px,leftmarginwillbesetbythebrowser
</style>

Hereisanexample:
Theaboveprogramwillproducethefollowingresult:

Themargin-bottom Property

Themargin-bottompropertyallows youtosetthebottommarginofanelement.It can


have a value in length, %, or auto.
Hereisanexample:
Theaboveprogramwillproducethefollowingresult:
Themargin-left 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:

Q3.Writethefew majordifferenceof outlineinCSS.


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

CSSstandsforCascadingStyleSheets.Itisasimpledesignlanguageintendedto simplify the


process of making web pages presentable.
Q2.WritethethreepartsofCSSsyntax? Answer
CSSstyleismadeofthreeparts:
1. Selector:AselectorisanHTMLtagatwhichastylewillbeapplied.Thiscould be any
tag like <h1>, <p> or <table> etc.
2. Property: A property is a type of attribute of HTML tag. Put simply, all the
HTMLattributesareconvertedintoCSSproperties.Theycouldbe color,border,
bgcolor etc.
3. Value:Valuesareassignedtoproperties.Forexample, colorpropertycanhave the
value either red or #F1F1F1 etc.

Checkyourprogress2

Q1.Whatarethe3typesofselectors.

Answer

Threetypes of CSS Selectors


1. TheElementselectors
2. TheID Selectors
3. TheClass Selectors

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

Youcanset the followingbackgroundpropertiesofan element:

 Thebackground-imagepropertyis usedto setthebackgroundimageof an element.


 Thebackground-repeatpropertyisusedtocontroltherepetitionofanimageinthe
background.
 Thebackground-positionpropertyisusedtocontrolthepositionofanimageinthe
background.
 Thebackground-attachmentpropertyisusedtocontrolthescrollingofanimagein the
background.
 Thebackgroundpropertyisusedasshorthandtospecifyanumberofother
background properties.
Checkyourprogress4

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.

Q2.Whatarethedifferentvaluesoforderedandunorderedlistin CSS? Answer

Thevalues,foranunorderedlist: disc

(default),Circle,Square.

Thevalues, for anordered list:

Decimal,decimal-leading-zero,lower-alpha,upper-alpha,lower-roman,upper-roman.

Checkyourprogress6

Q1.Writethedifferentpropertiesof thedimensionsofabox. Answer


Propertiesofdimensions ofabox.

 Theheightpropertyis used to set theheight of abox.


 Thewidth propertyis used to set thewidth of abox.
 Theline-heightpropertyis used toset theheightofalineof text.
 The max-heightpropertyisused tosetamaximumheight thatabox can be.
 The min-heightpropertyisusedtosettheminimumheightthatabox can be.
 Themax-widthpropertyisused toset themaximumwidth thataboxcan be.
 Themin-widthpropertyis usedtoset theminimumwidththat aboxcan be.
Q2.Writethethreepropertiesofborder. Answer
Therearethreepropertiesof a border:

 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;

Thevalues ofdisplayproperty havethefollowing meanings:

 Block -Thisvaluecauses anelement togenerateablockbox.


 Inline-block- This value causes an element to generate an inline-level block
container. The inside of an inline-block is formatted as a block box, and the
element itself is formatted as an atomic inline-level box.
 Inline -Thisvaluecausesanelementtogenerateoneormore inline
boxes.
 list-item -Thisvaluecausesanelement(e.g.,LIinHTML)togenerate a
principal block box and a marker box.
 None -Thisvaluecausesanelementtonotappearinthe formatting
structure

Herearesome examples ofthedisplayproperty:


p {display:block}
em{display:inline}
li{ display:list-item}
SettingwidthandMaxwidthusing CSS
Settingthewidthofablock-level elementwillpreventitfromstretchingouttothe
edgesofitscontainer.Then,youcansetthemarginstoauto,tohorizontallycenter the
element within its container. The element will take up the specified width, and the
remaining space will be split equally between the two margins:

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.

Usingmax-widthinstead, in this situation, will improve the browser's handling of


small windows. This is important when making a site usable on small devices:

This<div>elementhasamax-widthof500px,andmargin set
to auto.

Tip:Resizethebrowserwindowtolessthan500pxwide,toseethedifference between the


two divs!

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

An element with position: absolute is positioned at the specified coordinates relative


to your screen top-left corner. You can use two values top and left along with the
position property to move an HTML element anywhere in HTML document.

 MoveLeft-Useanegativevaluefor left.
 MoveRight-Useapositivevalueforleft.
 MoveUp-Use anegativevalue for top.
 MoveDown-Useapositivevalue fortop.

NOTE:Youcanusebottomorrightvaluesaswellinthesameway astopand left.


Hereisanexample:
<div style="position: absolute; left: 80px; top: 20px; background-color:
yellow ;">
This divhas absolute positioning.

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:

<div style="position:fixed;left:80px;top:20px; background-


color:yellow;">
Thisdivhasfixed positioning.
</div>

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).

Property Description Values CSS


clear Specifies which sides of left right 1
an element where other bothnone
floatingelementsarenot inherit
allowed
float Specifieswhetherornot a leftright 1
box should float none
inherit
Example:

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.

Center Align Elements

To horizontally center a block element (like <div>), usemargin: auto;


Setting the width of the element will prevent it from stretching out to the edges of
its container.Theelement will thentakeup thespecified width, and the remaining
space will be split equally between the two margins:

Page83
Example:

.center
{
margin:auto;
width: 50%;
border:3pxsolidgreen; padding:
10px;
}

Note:Centeraligninghasnoeffectifthewidthpropertyisnotset(orsetto 100%).

Center Align Text

Tojustcenterthetextinsideanelement,usetext-align:center; Example:

.center
{
text-align: center;
border:3pxsolidgreen;
}
CenteranImage

Tocenteranimage,usemargin:auto;andmakeitintoablockelement:
img
{
display:block;
margin: auto;
width: 40%;
}

Leftand RightAlign-Using position

Onemethodforaligningelements isto use position: absolute;:

Example:

.right{
position:absolute;
right: 0px;
width:300px;
border:3pxsolid#73AD21;
padding: 10px;
}

Note:Absolutepositionedelementsareremovedfromthenormalflow, and can


overlap elements.

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;
}

Matchthefirst<i> element inall<p>elements


Inthe followingexample,theselectormatchesthe first<i>elementin all
<p> elements:

Example
pi:first-child
{
color:blue;
}

Selector Example Exampledescription


:active a:active Selectstheactive link

:checked input:checked Selectseverychecked<input>


element

:disabled input:disabled Selectseverydisabled<input>


element

Page89
:empty p:empty Selectsevery<p>elementthat
has no children

:enabled input:enabled Selectseveryenabled<input>


element

:first-child p:first-child Selectsevery<p>elementstha


tis the first child of its parent
Selectsevery<p>elementthati
:first-of-type p:first-of-type
s
thefirst<p>elementofitsparen
t

:focus input:focus Selectsthe<input>elementth


at has focus
:hover a:hover Selectslinksonmouse over

:in-range input:in-range Selects<input>elementswith


a value within a specified
range

:invalid input:invalid Selectsall<input>elementswi


th an invalid value
Selectsevery<p>elementwit
:lang(language) p:lang(it) ha lang attribute value
starting with "it"

:last-child p:last-child Selectsevery<p>elementstha


tis the last child of its parent

:last-of-type p:last-of-type Selectsevery<p>elementthat


is
thelast<p>elementofitsparen
t
:link a:link Selectsallunvisited links

:not(selector) :not(p) Selectseveryelementthatisnota


<p>element

:nth-child(n) p:nth-child(2) Selectsevery<p>elementthati


s the second child of its
parent

:nth-last- p:nth-last- Selectsevery<p>elementthati


child(n) child(2) s the second child of its
parent, counting from the
last child

:nth-last-of- p:nth-last- Selects every <p> element


type(n) of- type(2) that is the second <p>
element of its
parent,countingfromthelastch
ild

Page90
p:nth-of- Selectsevery<p>elementthati
:nth-of-type(n) type(2) s the second <p> element of
its parent

:only-of-type p:only-of- Selects every <p> element


type that is
theonly<p>elementofitspare
nt

:only-child p:only-child Selectsevery<p>elementthati


s the only child of its parent
:optional input:optional Selects<input>elementswith no

"required"attribute

:out-of-range input:out- Selects<input>elementswith


of- range a value outside a specified
range

:read-only input:read- Selects<input>elementswith


only a "readonly" attribute
specified

:read-write input:read- Selects<input>elementswith


write no "readonly" attribute

:required input:required Selects<input>elementswith


a "required" attribute
specified
:root root Selectsthedocument'srootelement
Selectsthecurrentactive#new
:target #news:target s element (clicked on a URL
containing that anchor
name)

:valid input:valid Selectsall<input>elementswit


ha valid value
:visited a:visited Selectsallvisitedlinks

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

The: beforepseudo-element can beusedto insertsomecontent beforethe


contentofanelement.Thefollowingexampledemonstrateshowtouse
:before element toadd some contentbeforeanyelement.

<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

The:afterpseudo-element can be used to insert some content after the


content of an element. The following example demonstrates how to use:
after element to add some content after any 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)

Navigation Bar= List of Links


A navigation bar needs standard HTML as a base. In our examples we will build
the navigation bar from a standard HTMLlist.A navigation bar is basically a list of
links, so using the <ul> and <li> elements makes perfect sense: Example
<ul>
<li><ahref="default.asp">Home</a></li>
<li><ahref="news.asp">News</a></li>
<li><ahref="contact.asp">Contact</a></li>
<li><ahref="about.asp">About</a></li>
</ul>

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

Addtext-align:center to<li>or<a>tocenterthe links.Add the borderproperty to


<ul>addaborderaroundthenavbar.Ifyoualsowantbordersinsidethenavbar, add
aborder-bottom to all <li> elements, except for the last one:

<!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

Images play an important role in any webpage. Though it is not recommended to


include a lot of images, but it is still important to use good images wherever
required.CSS plays a good role to control image display. You can set the following
image properties using CSS.

Theborderpropertyis usedto setthewidthof animageborder.


 Theheightpropertyis used to set theheight of animage.
 Thewidth propertyisused to set thewidth of an image.
 The-moz-opacity propertyis used toset theopacityof an image.

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.

 p[lang]-Selectsallparagraph elementswithalang attribute.


 p[lang="fr"]- Selects all paragraph elements whose lang attribute has a
value of exactly "fr".
 p[lang~="fr"]-Selectsallparagraphelementswhoselangattributecontains
the word "fr".
 p[lang|="en"]-Selectsallparagraphelementswhoselangattributecontains
values that are exactly "en", or begin with "en-".

Multiple Style Rules


You may need to define multiple style rules for a single element. You can define
these rules to combine multiple properties and corresponding values into a single
block as defined in the following example:
h1 {
color:#36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom:1em;
text-transform:lowercase;
}
Here all the property and value pairs are separated by a semicolon (;). You can
keeptheminasinglelineormultiplelines.Forbetterreadability,wekeepthemin separate
lines.

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

The[attribute="value"]selectorisusedtoselectelementswithaspecified attribute and


value.
Thefollowingexampleselects all<a>elements withatarget="_blank"attribute:
Example

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

The[attribute|="value"] selector is used to select elements with the specified


attribute starting with the specified value. The following example selects all
elements with a class attribute value that begins with "top": Note:The value hasto
be a whole word, either alone, like class="top", or followed by a hyphen( - ), like
class="top-text"!
Example
[class|="top"] {
background:yellow;
}

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

The [attribute*="value"] selector is used to select elements whose attribute value


containsaspecifiedvalue.Thefollowingexampleselectsallelementswithaclass attribute
value that contains "te":
Note:Thevaluedoesnothavetobeawholeword! Example:

[class*="te"] {
background:yellow;
}

Checkyourprogress2

Q1.Writethedifferentpropertiesof image?

Answer:

Q2.WhatisPseudoClass ?
Answer:

Q3. Whatis navigationbar?

Answer:

Page108
Letus sumup
In this unit we have understood padding using CSS,setting

displayusingCSS,settingwidthandmaxwidthusingCSS,settingfloatproper

ty using CSS,inline block propertry,horizontal allignment in

CSS,working

withcombinatory,pseudo-class,pseudo-elements,creatinganavigationbar, working

with images,attribute selectors.

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?

AnswerTheborderpropertyisusedtosetthewidthofanimageborder. The height

property is used to set the height of an image.

Thewidth propertyisused to set thewidth of an image.

Q2.WhatisPseudoClass? Answer

Apseudo-classis usedtodefineaspecialstate ofan element

Q3.Whatisnavigationbar? Answer

A navigation bar (or navigation system) is a section of a graphical user interface


intendedtoaidvisitorsinaccessinginformation.Navigationbarsareimplementedin file browsers,
web browsers and as a design element of some web sites

What is xml

o Xml (eXtensible Markup Language) is a mark up language.


o XML is designed to store and transport data.
o Xml was released in late 90’s. it was created to provide an easy to use and store self describing
data.
o XML became a W3C Recommendation on February 10, 1998.
o XML is not a replacement for HTML.
o XML is designed to be self-descriptive.
o XML is designed to carry data, not to display data.
o XML tags are not predefined. You must define your own tags.
o XML is platform independent and language independent.

What is mark-up language


A mark up language is a modern system for highlight or underline a document.

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.

Features and Advantages of XML


1
XML is widely used in the era of web development. It is also used to simplify data storage and data
sharing.

The main features or advantages of XML are given below.

1) XML separates data from HTML


If you need to display dynamic data in your HTML document, it will take a lot of work to edit the HTML
each time the data changes.

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.

2) XML simplifies data sharing


In the real world, computer systems and databases contain data in incompatible formats.

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.

3) XML simplifies data transport


One of the most time-consuming challenges for developers is to exchange data between incompatible
systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be read by different
incompatible applications.

4) XML simplifies Platform change


Upgrading to new systems (hardware or software platforms), is always time consuming. Large amounts
of data must be converted and incompatible data is often lost.

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.

5) XML increases data availability


Different applications can access your data, not only in HTML pages, but also from XML data sources.

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.

6) XML can be used to create new internet languages


A lot of new Internet languages are created with XML.

Here are some examples:

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".

Example of XML Document


XML documents uses a self-describing and simple syntax:

1. <?xml version="1.0" encoding="ISO-8859-1"?>


2. <note>
3. <to>Tove</to>
4. <from>Jani</from>
5. <heading>Reminder</heading>
6. <body>Don't forget me this weekend!</body>
7. </note>
The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO-
8859-1 = Latin-1/West European character set).

There are many video formats out there.

The MP4, WebM, and Ogg formats are


supported by HTML.

The MP4 format is recommended by YouTube.

Format File Description

MPEG .mpg MPEG. Developed by the Moving Pictures


.mpeg Expert Group. The first popular video format on
the web. Not supported anymore in HTML.

AVI .avi AVI (Audio Video Interleave). Developed by


Microsoft. Commonly used in video cameras
and TV hardware. Plays well on Windows
computers, but not in web browsers.

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.

QuickTime .mov QuickTime. Developed by Apple. Commonly


used in video cameras and TV hardware. Plays
well on Apple computers, but not in web
browsers.

RealVideo .rm RealVideo. Developed by Real Media to allow


.ram video streaming with low bandwidths. Does not
play in web browsers.

Flash .swf Flash. Developed by Macromedia. Often


.flv requires an extra component (plug-in) to play in
web browsers.

Ogg .ogg Theora Ogg. Developed by the Xiph.Org


Foundation. Supported by HTML.

WebM .webm WebM. Developed by Mozilla, Opera, Adobe,


and Google. Supported by HTML.

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.

You might also like