Module 1
Module 1
Hypertext Markup Language (HTML) is the standard markup language for documents designed to be
displayed in a web browser. It can be assisted by technologies such as Cascading Style Sheets (CSS) and
scripting languages such as JavaScript.
It is the most widely used language on Web to develop web pages. HTML was created by Berners-Lee in
late 1991 but "HTML 2.0" was the first standard HTML specification which was published in 1995.
A markup language is simply a way of annotating a document in such a way as to make the annotations
distinct from the text being annotated. Markup languages such as HTML, Tex, XML, and XHTML allow
users to control how text and visual elements will be laid out and displayed.
Hypertext is text which is not constrained to be linear. It is a text which contains links to other texts.
Hypermedia is a term used for hypertext which is not constrained to be text. It can include graphics, video
and sound.
Web browsers evolved into quite permissive and lenient programs. They could handle sloppy HTML,
missing or malformed tags, and other syntax errors. However, it was somewhat unpredictable how each
browser would handle such errors.
XHTML
XHTML stands for Extensible Hyper Text Markup Language. It is identical to HTML that uses stricter
XML (extensible markup language) syntax rules. The goal of XHTML with its strict rules was to make
page rendering more predictable by forcing web authors to create web pages without syntax errors.
Two versions of XHTML were created:
HTML validators provide the means of verifying that web pages follow the rules for XHTML Transitional
or Strict. The strict version was meant to be rendered
XML
XML is a textual markup language. Also like HTML, the formal rules for XML were set by the W3C.
XML is a more general markup language than HTML. It is (and has been) used to mark up any type of
data. XML-based data formats (called schemas in XML) are almost everywhere. For instance, Microsoft
Office products.
HTML5
At around the same time the XHTML 2.0 specification was being developed, a group of developers at
Opera and Mozilla formed the WHATWG (Web Hypertext Application Technology Working Group)
group within the W3C.
The work at WHATWG progressed quickly, and eventually, by 2009, the W3C stopped work on XHTML
2.0 and instead adopted the work done by WHATWG and named it HTML5.
There are three main aims to HTML5:
1. Specify unambiguously how browsers should deal with invalid markup.
2. Provide an open, nonproprietary programming framework (via JavaScript) for creating rich web
applications.
3. Be backwards compatible with the existing web.
HTML vs HTML5
HTML5 was developed by a group known as WHATWG and was designed to improve upon the previous
HTML versions and solve some cross-browser compatibility issues. The key differences between HTML
and HTML5:
• HTML5 offers better support for various forms of media, such as audio and video, by providing
tags for them. HTML didn’t have these tags and relied on third-party plug-in.
• HTML doesn’t allow JavaScript to run in the browser. HTML5 solved this problem by introducing
the JS Web Worker API. Now, because of the native support of JavaScript, web pages can be better
designed by using front-end scripts to enhance the user experience.
• HTML5 includes new input attributes, such as email, URLs, date and time, search, etc.
• HTML5 is device independent and has better browser compatibility than previous HTML versions.
• HTML5 has better parsing (parsing is the processing of text) rules and allows for greater flexibility
in parsing than HTML.
• HTML5 also makes it easy to find the location without any third-party plugins.
• HTML5 also has native support for vector graphics, so, there is no need of third-party software
such as Adobe Flash.
In short, HTML5 is a better version of HTML with added features and functionalities.
HTML vs XHTML
XHTML was developed as an extension to HTML. There aren’t many differences between HTML4 and
XHTML, and XHTML is basically a stricter version of HTML4. The main differences between HTML and
XHTML are:
• HTML4 allows some elements to omit the end tag. End tags are added when closing a certain part
of the text, such as a paragraph. They are usually symbolized with a backslash (for example,
opening tag of a paragraph is <p> while end tag is </p>). XHTML requires that all elements
include the end tag.
• HTML4 allows overlapping of certain elements. XHTML doesn’t allow any elements to overlap.
• Attribute values (such as font size) have to be quoted in XHTML, even if they are numeric. HTML
doesn’t have include quoted values for attributes.
• Attributes cannot be minimized in HTML.
• There is a small difference in the way empty elements are handled.
While the above are the more important differences, there are also some very subtle differences, but they
are really rare to run into. You can always check out the documentation of XHTML for more information.
The takeaway is that XHTML was designed to solve some problems in HTML, by incorporating some
features of XML.
HTML5 vs XHTML
Since XHTML and HTML are largely the same, the differences between XHTML and HTML5 are the
same as the ones between HTML4 and HTML5. However, the following are some of the subtler
differences between HTML5 and XHTML:
• While XHTML is case sensitive, HTML5 is not (HTML is also case insensitive).
• HTML5 has a much simpler doctype than XHTML and HTML (Doctypes tell the browser how to
interpret the data).
• HTML5 is compatible with all browsers while XHTML isn’t.
• HTML5 is more lenient, following the footsteps of HTML4, than XHTML.
• HTML5 is better suited for mobile devices such as tablets and phones, while XHTML is better
suited for computer screens.
• HTML Syntax
HTML documents are composed of textual content and HTML elements. HTML tags are element names
surrounded by angle brackets:
<tagname>content goes here...</tagname>
HTML elements can also contain attributes. An HTML attribute is a name=value pair that provides more
information about the HTML element. In XHTML, attribute values had to be enclosed in quotes; in
HTML5, the quotes are optional.
An empty HTML element does not contain any text content, instead it is an instruction to the browser to
do something. Perhaps the most common empty element is <img>, the image element. In XHTML, empty
elements had to be terminated by a trailing slash (as shown in Figure 2.4). In HTML5, the trailing slash in
empty elements is optional.
• Semantic Markup:
Semantic markup is used to reinforce the semantics (meaning) of information in WebPages/web
application rather than to define presentation or look.
Ex: Non semantic elements: <div>, <span> etc... – tells nothing about the content
Semantic elements : <form>, <table>, <article> etc… -clearly defines the content
Eliminating presentation-oriented markup and writing semantic HTML markup has a variety of important
advantages:
▪ Maintainability- Semantic markup is easier to update and change than web pages that contain a
great deal of presentation markup.
▪ Faster- Semantic web pages are typically quicker to author and faster to download.
▪ Accessibility-Not all web users are able to view the content on web pages. Users with sight
disabilities experience the web using voice reading software. Visiting a web page using voice
reading software can be a very frustrating experience if the site does not use semantic markup. As
well, many governments insist that sites for organizations that receive federal government funding
must adhere to certain accessibility guidelines.
▪ Search engine optimization- For many site owners, the most important users of a website are the
various search engine crawlers. These crawlers are automated programs that cross the web
scanning sites for their content, which is then used for users’ search queries. Semantic markup
provides better instructions for these crawlers: it tells them what things are important content on
the site.
DOCTYPE
The DOCTYPE (Document Type Definition) element, which tells the browser (or any other client
software that is reading this HTML document) what type of document it is about to process (it does not
indicate what version of HTML) It must only appear once, at the top of the page (before any HTML tags).
The <!DOCTYPE> declaration is not case sensitive.
The <html> element is sometimes called the root element as it contains all the other HTML elements in
the document.
HTML pages are divided into two sections: the head and the body, which correspond to the <head> and
<body> elements.
The head contains descriptive elements about the document, such as its title, any style sheets or JavaScript
files it uses, and other types of Meta information used by search engines and other programs. Body
contains the visible page content.
There are several tags that go inside the head section of an HTML document.
1. The <base> tag: The <base> tag acts as a reference point for all the links on a page. This reference
point is specified with the <base> tag's href attribute.
Now whenever you need to display an image on your page, you can do so by specifying the name of
the image by its name alone, as in <img src="img1.jpg" />, <img src="img2.jpg" />, and so on, and the
browser will automatically look for it in http://www.somewebsite.com/images/.
2. The <link> tag :The <link> tag defines a relationship between two documents. It is used to define the
relationship between the document where it is located and another document. A common use of
the <link> tag is to call an external style sheet:
3. The <meta> tag:The <meta> tag is one of the most important tags in HTML. The <meta> tag is used
to describe the page in some way as well as other things such as refreshing a page automatically after a
certain amount of time, and preventing WebPages from being displayed in another websites frames
page. Some of the things that can be described using the <meta> tag include the pages author, the
software used to create the page, and a description of the content on the page.
4. The <script> tag: The <script> tag is used to place scripts on a webpage. When using
the <script> tag, you have to use its type attribute to specify the language the script is written in.
5. The <style> tag :The <style> tag is used to declare an internal stylesheet. The <style> tag specifies the
content type of a stylesheet with its type attribute which should be set to "text/css".
6. The <title> tag : The <title> tag declares the title for a webpage. The title of a webpage can be seen in
the top left corner of the web browser. If you look at the top left corner of your web browser window
right now, you will see the title HTML head section, as that is the title of this page.
Often an HTML element will contain other HTML elements. In such a case, the container element is said
to be a parent of the contained, or child, element. Any elements contained within the child are said to be
descendants of the parent element; likewise, any given child element, may have a variety o f ancestors.
1. HTML Headings
HTML headings are defined with the <h1> to <h6> tags. <h1> defines the most important
heading. <h6> defines the least important heading. Search engines use the headings to index the structure
and content of your web pages. Users often skim a page by its headings. It is important to use headings to
show the document structure.
Ex:
Paragraphs, the most basic unit of text in an HTML document. <p> tag is a container and can contain
HTML and other inline HTML elements like <strong> and <a> elements.
<p>This is a paragraph.</p>
<p>This is another with break <br> paragraph.</p>
<div> element is also a container element and is used to create a logical grouping of content (text and other
HTML elements, including containers such as <p> and other <div> elements).
Ex:
EX2:
The HTML <pre> element defines preformatted text. The text inside a <pre> element is displayed in a
fixed-width font (usually Courier), and it preserves both spaces and line breaks:
3. Links
HTML links are hyperlinks. You can click on a link and jump to another document. Links are created
using the <a> element (the “a” stands for anchor). A link has two main parts: the destination and the label.
As can be seen in Figure 2.15, the label of a link can be text or another HTML element such as an image.
You can use the anchor element to create a wide range of links. These include:
■ Links to external sites (or to individual resources such as images or movies on an external site).
■ Links to other pages or resources within the current site.
■ Links to other places within the current page.
■ Links to particular locations on another page (whether on the same site or on an external site).
■ Links that are instructions to the browser to start the users email program.
■ Links that are instructions to the browser to execute a JavaScript function.
■ Links that are instructions to the mobile browser to make a phone call.
The href Attribute : HTML links are defined with the <a> tag. The link address is specified in
the href attribute:
<a href="https://www.w3schools.com">This is a link</a>
Example:
Relative filepath: It points to file relative to current page. It refers to same server of the HTML document.
If URL does not include “https:// ” , then the browser will request the current server for file. Table below
gives sample relative referencing.
Inline elements are those that do not disrupt the flow of text (i.e., cause a line break). HTML defines over
30 of these elements. Table 2.2 lists some of the most commonly used of these elements.
<!DOCTYPE html>
<html>
<head>
<title>My First HTML</title>
<meta charset="ANSI">
</head>
<body>
<!-- This is a comment -->
<p>This is a paragraph.</p>
<em>Emphasized text</em><br>
Prof.Vidya Y, Dr. Anjan Kumar K N, Dept of CSE, RNSIT Page 14
WEB TECHNOLOGY AND ITS APPLICATIONS [18CS63]
<p><strong>Note:</strong> The mark tag is not supported in Internet Explorer 8 and earlier
versions.</p>
<p>This is a <u>parragraph</u>.</p>
<p>He named his car <i>The lightning</i>, because it was very fast.</p>
</body>
</html>
Output:
5. Images
HTML images are defined with the <img> tag. The source file (src), alternative text (alt), width,
and height are provided as attributes
The src Attribute: HTML images are defined with the <img> tag. The filename of the image source is
specified in the src attribute:
<img src="img_girl.jpg">
The width and height Attributes : HTML images also have width and height attributes, which specifies the
width and height of the image:
<img src="img_girl.jpg" width="500" height="600">
The alt Attribute : The alt attribute specifies an alternative text to be used, if an image cannot be displayed.
The value of the alt attribute can be read by screen readers. This way, someone "listening" to the webpage,
e.g. a vision impaired person, can "hear" the element.
<img src="img_girl.jpg" alt="Girl with a jacket">
Example:
6. Character Entities
Character entity are special characters for symbols for which there is either no easy way to type them via a
keyboard (such as the copyright symbol or accented characters) or which have a reserved meaning in
HTML (for instance the “<” or “>” symbols). There are many HTML character entities. They can be used
in an HTML document by using the entity name or the entity number. Some of the most common are listed
in Table 2.3.
7. Lists
The most common block-level elements in HTML are list. HTML provides three types of lists:
■ Unordered lists. Collections of items in no particular order; these are by default rendered by the
browser as a bulleted list. However, it is common in CSS to style unordered lists without the
bullets. Unordered lists have become the conventional way to mark-up navigational menus.
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
■ Ordered lists. Collections of items that have a set order; these are by default rendered by the
browser as a numbered list. An ordered list starts with the <ol> tag. Each list item starts with
the <li> tag.
■ Definition lists. Collection of name and definition pairs. These tend to be used infrequently
The <dd> tag is used to describe a term/name in a description list.
The <dd> tag is used in conjunction with <dl> (defines a description list) and <dt> (defines
terms/names). Inside a <dd> tag you can put paragraphs, line breaks, images, links, lists, etc.
.
Most website pages have a recognizable header and footer section. The header element contains the site
logo and title (and perhaps additional subtitles or taglines), horizontal navigation links, and perhaps one or
two horizontal banners.
Header can contain multiple headings in close proximity. The <hgroup> element can be used in such a
circumstance to group them together within one container. The <hgroup> element can be used in contexts
other than a header. For instance, one could also use an <hgroup> within an <article> or a <section>
element as well. The <hgroup> element can only contain <h1>, <h2>, etc., elements
The typical footer contains information such as smaller text versions of the navigation, copyright notices,
information about the site’s privacy policy, and perhaps twitter feeds or links to other social sites.
1. Example: Footer
2. Example: Header
Navigation
The <nav> element represents a section of a page that contains links to other pages or to other parts within
the same page. Like the other new HTML5 semantic elements, the browser does not apply any special
presentation to the <nav> element. Not all links of document should be inside a <nav> element. The <nav>
element is intended only for major block of navigation links.
• Forum post
• Blog post
• Newspaper article
The <section> element defines a section in a document. According to W3C's HTML5 documentation: "A
section is a thematic grouping of content, typically with a heading." A home page could normally be split
into sections for introduction, content, and contact information.
▪ <img> element is used to display an image such as a photograph or illustration. It includes a link to
the image file, which is typically a .jpg, .png or .gif. ...
▪ <figure> element is used as a container to hold an image, graph or other illustration. ..
Aside
The <aside> element is similar to the <figure> element in that it is used for marking up content that is
separate from the main content on the page.
The <aside> element is used for sidebars, pull quotes, groups of advertising images, or any other grouping
of non-essential elements.
When tags like <font> and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large websites, where fonts and color
information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
• Cascading Style Sheets (CSS) is a W3C standard style sheet language used to describe
the presentation of a document written in HTML or XML (including XML dialects such
as SVG, MathML or XHTML).
• CSS describes how elements should be rendered on screen, on paper, in speech, or on
other media. With CSS, designer can assign font properties, colors, sizes, borders,
background images, and even position elements on the page
• CSS can be added directly to any HTML element (via the style attribute), within the
<head> element, or, most commonly, in a separate text file that contains only CSS.
Benefits of CSS:
• Improved page download speed: A site built using a centralized set of CSS files for all
presentation will also be quicker to download because each individual HTML file will
contain less style information and markup, and thus be smaller.
• Improved output flexibility: CSS can be used to adopt a page for different output
media. This approach to CSS page design is often referred to as responsive design.
CSS Versions
In the early 1990s, a variety of different style sheet standards were proposed, including
JavaScript style sheets, which was proposed by Netscape in 1996. Netscape’s proposal was one
that required the use of JavaScript programming to perform style changes. Thankfully for
nonprogrammers everywhere, the W3C decided to adopt CSS, and by the end of 1996 the CSS
Level 1 Recommendation was published.
A year later, the CSS Level 2 Recommendation (also more succinctly labeled simply as
CSS2) was published. Even though work began over a decade ago, an updated version of the
Level 2 Recommendation, CSS2.1, did not become an official W3C Recommendation until June
2011. And to complicate matters even more, all through the last decade (and to the present day as
well), during the same time the CSS2.1 standard was being worked on, a different group at the
W3C was working on a CSS3 draft.
To make CSS3 more manageable for both browser manufacturers and web designers, the
W3C has subdivided it into a variety of different CSS3 modules. So far the following CSS3
modules have made it to official W3C Recommendations: CSS Selectors, CSS Namespaces, CSS
Media Queries, and CSS Color.
• Selectors are a pattern that is used by the browser to select the HTML elements that will
receive the style.
• The declaration block contains one or more declarations separated by semicolons.
• Each declaration includes a CSS property name and a value, separated by a colon.
• A CSS declaration always ends with a semicolon, and declaration blocks are surrounded
by curly braces.
• A CSS document consists of one or more style rules
• A rule consists of a selector that identifies the HTML element or elements that will be
affected, followed by a series of property: value pairs (each pair is also called a
declaration)
• The series of declarations is also called the declaration block.
• A declaration block can be together on a single line, or spread across multiple lines. The
browser ignores white space (i.e., spaces, tabs, and returns) between your CSS rules so
you can format the CSS however you want.
• Notice that each declaration is terminated with a semicolon.
• The semicolon for the last declaration in a block is in fact optional.
<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red;
text-align: center;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>These paragraphs are styled with CSS.</p>
</body>
</html>
Properties
Values
• The unit of any given value is dependent upon the property.
• Some property values are from a predefined list of keywords. Others are values such as
length measurements, percentages, numbers without units, color values and URLs.
• CSS supports a variety of different ways of describing color. Table below lists the
different ways you can describe a color value in CSS.
There are multiple ways of specifying color in CSS and also for specifying a unit of
measurement. These units can sometimes be complicated to work with.
When working with print design, we generally make use of straightforward absolute units such
as inches or centimeters and picas or points. However, because different devices have differing
physical sizes as well as different pixel resolutions and because the user is able to change the
browser size or its zoom mode, these absolute units don’t always make sense with web element
measures.
Table lists the different units of measure in CSS. Some of these are relative units, in that they
are based on the value of something else, such as the size of a parent element. Others are
absolute units, in that they have a real-world size. Unless you are defining a style sheet for
printing, it is recommended you avoid using absolute units. Pixels are perhaps the one popular
exception
• Inline style
Inline styles: An inline style may be used to apply a unique style for a single element. To use
inline styles, add the style attribute to the relevant element. The style attribute can contain any
CSS property.
An inline style only affects the element it is defined within and overrides any other style
definitions for properties used in the inline style. Notice that a selector is not necessary with
inline styles and that semicolons are only required for separating multiple rules.
Using inline styles is generally discouraged since they increase bandwidth and decrease
maintainability (because presentation and content are intermixed and because it can be difficult
to make consistent inline style changes across multiple files). Inline styles can, however, be
handy for quickly testing out a style change.
Output:
Embedded style sheet: Embedded style sheets (also called internal styles) are style rules
placed within the <style> element (inside the <head> element of an HTML document) as shown
in example. Since each HTML document has its own <style> element, it is more difficult to
consistently style multiple documents when using embedded styles.
Just as with inline styles, embedded styles can, however, be helpful when quickly testing
out a style that is used in multiple places within a single HTML document.
Output:
External style sheet: External style sheets are style rules placed within an external text file
with the .css extension. This is by far the most common place to locate style rules because it
provides the best maintainability. When you make a change to an external style sheet, all HTML
documents that reference that style sheet will automatically use the updated version.
The browser is able to cache the external style sheet, which can improve the performance
of the site as well. To reference an external style sheet, you must use a <link> element (within
the <head> element. Several style sheets can be linked at a time; each linked style sheet will
require its own <link> element.
Mystyle.css
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Output:
Cascading Order: All the styles in a page will "cascade" into a new "virtual" style sheet by the
following rules, where number one has the highest priority:
3. Browser default
So, an inline style has the highest priority, and will override external and internal styles and
browser defaults.
Output:
2.4 Selectors: Selectors are used to "find" (or select) HTML elements based on their element
name, id, class, attribute, and more.
When defining CSS rules, selector must be used first to tell the browser which elements
will be affected by the property values. CSS selectors allow selecting individual or multiple
HTML elements. The three basic selector types that have been around since the earliest CSS2
specification are:
1. Element selectors: The element selector selects elements based on the element name. It
selects all instances of a given HTML element. The example CSS rules in example illustrate
two element selectors. All elements can be selected by using the universal element selector,
which is the * (asterisk) character.
Example 1:
Output:
Example 2:
Output:
2. Grouped selector: Group selectors are used for the same declaration
in CSS to shrink style sheets. CSS allows grouping multiple selectors that
share the same declaration. This optimization technique allows applying
the same style to multiple elements to save space Grouping is used when
elements are with the same style definitions.
Example 1:
Example 2:
Id selectors should only be used when referencing a single HTML element since an id attribute
can only be assigned to a single HTML element. Class selector can be used when referencing
several related elements.
Example 2:
5. Attribute Selectors: An attribute selector provides a way to select HTML elements either
by the presence of an element attribute or by the value of an attribute. This can be a very
powerful technique, but because of uneven support by some of the browsers it is not widely used.
Attribute selectors can be a very helpful technique in the styling of hyperlinks and images.
[title] { … } This will match any element in the document that has a title attribute.
Syntax
selector::pseudo-element {
property:value;
}
The most common use of this type of selectors is for targeting link states. By default, the browser
displays link text blue and visited text links purple. Listing below illustrates the use of pseudo-
class selectors to style not only the visited and unvisited link colors, but also the hover color,
which is the color of the link when the mouse is over the link.
Do be aware that this state does not occur on touch screen devices. Note the syntax of
pseudo-class selectors: the colon (:) followed by the pseudo-class selector name. Do be aware
that a space is not allowed after the colon.
Output:
7. Contextual Selectors: A contextual selector (in CSS3 also called combinators) allows
selecting elements based on their ancestors, descendants, or siblings.
That is, it selects elements based on their context or their relation to other elements in the
document tree.
A descendant selector matches all elements that are contained within another element. The
character used to indicate descendant selection is the space character.
Descendant Selector : The descendant selector matches all elements that are descendants of a
specified element. The following example selects all <p> elements inside <div> elements:
Child Selector: The child selector selects all elements that are the immediate children of a
specified element. The following example selects all <p> elements that are immediate children
of a <div> element.
Adjacent Sibling Selector: The adjacent sibling selector selects all elements that are the
adjacent siblings of a specified element. Sibling elements must have the same parent element,
and "adjacent" means "immediately following". The following example selects all <p> elements
that are placed immediately after <div> elements:
General Sibling Selector: The general sibling selector selects all elements that are siblings of a
specified element. The following example selects all <p> elements that are siblings of <div>
elements.
Because
• There are three different types of style sheets (author-created, user-defined, and the
default browser style sheet).
• Author-created style sheets can define multiple rules for the same HTML element.
CSS has a system to help the browser determine how to display elements when different style
rules conflict.
The cascade is an algorithm that defines how to combine property values originating from
different sources. It lies at the core of CSS, as emphasized by the name: Cascading Style Sheets.
The “Cascade” in CSS refers to how conflicting rules are handled. The downward movement of
water down a cascade is meant to be analogous to how a given style rule will continue to take
precedence with child elements.
CSS uses the following cascade principles to help it deal with conflicts:
➢ Inheritance
➢ Specificity
➢ Location
Inheritance - Inheritance is the first of cascading principles. Many CSS properties affect not
only themselves but their descendants as well. Font, color, list, and text properties are
inheritable. Layout, sizing, border, background and spacing properties are not inheritable.
Figures illustrate CSS inheritance. In the first example, only some of the property rules are
inherited for the <body> element. That is, only the body element will have a thick green border
and the 100-px margin, however all the text in the other elements in the document will be in the
Arial font and colored red.
In the second example in Figure 2, it is assumed that there is no longer the body styling but
instead will have a single style rule that styles all the <div> elements. The <p> and <time>
elements within the <div> inherit the bold font-weight property but not the margin or border
styles.
However, it is possible to tell elements to inherit properties that are normally not inheritable,
as shown in 3rd Figure. In comparison to Figure 2nd, <p> elements nested within the <div>
elements now inherit the border and margins of their parent.
Figure 1: Inhereitence
• Specificity
Specificity is how the browser determines which style rule takes precedence when more than one
style rule could be applied to the same element. In CSS, the more specific the selector, the more
it takes precedence (i.e., overrides the previous definition).
The way that specificity works in the browser is that the browser assigns a weight to each style
rule, when several rules apply the one with the greatest weight takes precedence.
In the example shown in Figure below the color and font-weight properties defined in the
<body> element are inheritable and thus potentially applicable to all the child elements contained
within it. However, because the <div> and <p> elements also have the same properties set, they
override the value defined for the <body> element because their selectors (<div> and <p>) are
more specific. As a consequence, their font-weight is normal and their text is colored either
green or magenta.
As in Figure below, class selectors take precedence over element selectors, and id selectors take
precedence over class selectors. The precise algorithm the browser is supposed to use to
determine specificity is quite complex.
red
Green bold
green
Magenta
blue
Orange
• Location
When inheritance and specificity cannot determine style precedence, the principle of location
will be used. The principle of location is that when rules have the same specificity, then the latest
are given more weight. For instance, an inline style will override one defined in an external
author style sheet or an embedded style sheet.
Prof Vidya Y, Dr. Anjan Kumar K N, Dept. CSE, RNSIT Page 26
18CS63 – Web Technology and its Applications
Similarly, an embedded style will override an equally specific rule defined in an external author
style sheet if it appears after the external sheet’s <link> element. Styles defined in external
author style sheet X will override styles in external author style sheet Y if X’s <link> element is
after Y’s in the HTML document.
Similarly, the algorithm that is used to determine specificity of any given element is defined by
the W3C as follows.
■ First count 1 if the declaration is from a “style” attribute in the HTML, 0 otherwise (let that
value = a).
■ Count the number of ID attributes in the selector (let that value = b).
■ Count the number of class selectors, attribute selectors, and pseudo-classes in the selector (let
that value = c).
■ Count the number of element names and pseudo-elements in the selector (let that value = d).
■ finally, concatenate the four numbers a+b+c+d together to calculate the selector’s specificity.
Knowing the specificity algorithm is useful to debug a CSS problem. When the same style
property is defined multiple times within a single declaration block, the last one will take
precedence.
Figure illustrates how location affects precedence.
What would be the color of the sample text if there wasn’t an inline style definition?
It would be magenta.
All HTML elements can be considered as boxes. In CSS, the term "box model" refers to design
and layout. The CSS box model is essentially a box that wraps around every HTML element. It
consists of: Borders, margins, borders, padding, and the actual content. The image below
illustrates the box model:
• Background
As can be seen in Figure above, the background color or image of an element fills an element out
to its border. In contemporary web design, it has become extremely common to use CSS to
display purely presentational images (such as background gradients and patterns, decorative
images, etc.) rather than using the <img> element.
• Borders
The border-style property specifies what kind of border to display. Borders provide a way to
visually separate elements. Borders can be around all four sides of an element, or just one, two,
or three of the sides. Table below lists the various border properties.
Border widths are perhaps the one exception to the general advice against using the pixel
measure. Using em units or percentages for border widths can result in unpredictable widths as
the different browsers use different algorithms (some round up, some round down) as the zoom
level increases or decreases. For this reason, border widths are almost always set to pixel units.
Margins and padding are essential properties for adding white space to a web page, which can
help differentiate one element from another. Figure illustrates how these two properties can be
used to provide spacing and element differentia.
With border, margin, and padding properties, it is possible to set the properties for one or more
sides of the element box in a single property, or to set them individually using separate
properties.
Margins add spacing around an element’s content, while padding adds spacing within elements.
Borders divide the margin area from the padding area.Top and bottom margins of elements are
sometimes collapsed into a single margin that is equal to the larger of the two margins. This does
not happen on horizontal (left and right) margins. Only vertical (top and bottom) margins.
The W3C specification defines this behavior as collapsing margins: In CSS, the adjoining
margins of two or more boxes (which might or might not be siblings) can combine to form a
single margin. Margins that combine this way are said to collapse, and the resulting combined
margin is called a collapsed margin.
1. Adjacent siblings The margins of adjacent siblings are collapsed (except when the latter
sibling needs to be cleared past floats).
2. No content separating parent and descendants If there is no border, padding, inline
part, block formatting context created, or clearance to separate the margin-top of a block
from the margin-top of one or more of its descendant blocks; or no border, padding,
inline content, height, min-height, or max-height to separate the margin-bottom of a
block from the margin-bottom of one or more of its descendant blocks, then those
margins collapse. The collapsed margin ends up outside the parent.
3. Empty blocks If there is no border, padding, inline content, height, or min-height to
separate a block's margin-top from its margin-bottom, then its top and bottom margins
collapse.
Box Dimensions
Each box has a content area (e.g., text, an image, etc.) and optional surrounding padding, border,
and margin areas, the size of each area is specified by properties defined below:
The margin, border, and padding can be broken down into top, right, bottom, and left segments
(e.g., in the diagram, "LM" for left margin, "RP" for right padding, "TB" for top border, etc.).
The perimeter of each of the four areas (content, padding, border, and margin) is called an
"edge", so each box has four edges:
• Content edge or inner edge: The content edge surrounds the rectangle given by
the width and height of the box, which often depend on the element's rendered content.
The four content edges define the box's content box.
• Padding edge: The padding edge surrounds the box padding. If the padding has 0 width,
the padding edge is the same as the content edge. The four padding edges define the
box's padding box.
• Border edge: The border edge surrounds the box's border. If the border has 0 width, the
border edge is the same as the padding edge. The four border edges define the
box's border box.
• Margin edge or Outer edge: The margin edge surrounds the box margin. If the margin
has 0 widths, the margin edge is the same as the border edge. The four margin edges
define the box's margin box.
Each edge may be broken down into a top, right, bottom, and left edge.
The dimensions of the content area of a box — the content width and content height — depend
on several factors: whether the element generating the box has the 'width' or 'height' property set,
whether the box contains text or other boxes, whether the box is a table, etc.
Height Property:
The height property sets the height of an element. The height of an element does not include
padding, borders, or margins! If height: auto; the element will automatically adjust its height to
allow its content to be displayed correctly. If height is set to a numeric value (like pixels, (r)em,
percentages) then if the content does not fit within the specified height, it will overflow. How the
container will handle the overflowing content is defined by the overflow property.
Property Values
Value Description
length Defines the height in px, cm, etc. Read about length units
Overflow Property: The overflow property specifies what should happen if content overflow
an element's box. This property specifies whether to clip content or to add scrollbars when an
element's content is too big to fit in a specified area.
Note: The overflow property only works for block elements with a specified height.
Property Values
Value Description
visible The overflow is not clipped. It renders outside the element's box. This is default
hidden The overflow is clipped, and the rest of the content will be invisible
scroll The overflow is clipped, but a scroll-bar is added to see the rest of the content
auto If overflow is clipped, a scroll-bar should be added to see the rest of the content
Developer tools in current browsers make it significantly easier to examine and troubleshoot
CSS than was the case a decade ago.
Font Family
Web font stack- A font stack is a list of fonts in the CSS font-family declaration. The fonts are
listed in order of preference that would appear on the site in case of a problem like a font not
loading.
Font Family: The font family of a text is set with the font-family property. The font-family
property should hold several font names as a "fallback" system. If the browser does not support
the first font, it tries the next font, and so on. Start with the font you want, and end with a generic
family, to let the browser pick a similar font in the generic family, if no other fonts are available.
Font Style: The font-style property is mostly used to specify italic text.
This property has three values:
normal - The text is shown normally
italic - The text is shown in italics
oblique - The text is "leaning" (oblique is very similar to italic, but less supported)
Paragraph Properties:
Font Size: The font-size property sets the size of the text. Being able to manage the text size is
important in web design. However, you should not use font size adjustments to make paragraphs
look like headings, or headings look like paragraphs. Sizing with pixels provides precise control
to create web layouts that work well on different devices. Relative units such as em units or
percentages for font sizes must be given.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for paragraphs. The
font-size value can be an absolute or relative size.
• Absolute size: Sets the text to a specified size Does not allow a user to change the text
size in all browsers (bad for accessibility reasons). Absolute size is useful when the
physical size of the output is known
• Relative size: Sets the size relative to surrounding elements. Allows a user to change the
text size in browsers
Note: If you do not specify a font size, the default size for normal text, like paragraphs, is 16px
(16px=1em).
Set Font Size With Pixels: Setting the text size with pixels gives you full control over the text
size:
In the example above, the text size in em is the same as the previous example in pixels.
However, with the em size, it is possible to adjust the text size in all browsers. Unfortunately,
there is still a problem with older versions of IE. The text becomes larger than it should when
made larger, and smaller than it should when made smaller.
The solution that works in all browsers is to set a default font-size in percent for the <body>
element:
Font Variant
The font-variant property specifies whether or not a text should be displayed in a small-caps font.
In a small-caps font, all lowercase letters are converted to uppercase letters. However, the
converted uppercase letters appears in a smaller font size than the original uppercase letters in
the text.
Question Bank