Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Unit 3: Cascading Style Sheets

CSS Introduction
• CSS stands for Cascading Style Sheets
• CSS is the language used to style a Web page.
• It is the language for describing the presentation of Web pages, including colours,
layout, and fonts, thus making web pages presentable to the users.
• It is independent of HTML and can be used with any XML-based markup language.
• CSS is easy to learn and understand but it provides powerful control over the
presentation of an HTML document. Most commonly, CSS is combined with the
markup languages HTML or XHTML.
• CSS saves a lot of work. It can control the layout of multiple web pages all at once.
• External stylesheets are stored in CSS files
• Now let’s try to break the acronym:
• Cascading: Falling of Styles
• Style: Adding designs/Styling our HTML tags
• Sheets: Writing our style in different documents

Why CSS?
• CSS saves time: You can write CSS once and reuse the same sheet in multiple
HTML pages.
• Easy Maintenance: To make a global change simply change the style, and all
elements in all the webpages will be updated automatically.
• Search Engines: CSS is considered a clean coding technique, which means search
engines won’t have to struggle to “read” its content.
• Superior styles to HTML: CSS has a much wider array of attributes than HTML,
so you can give a far better look to your HTML page in comparison to HTML
attributes.
• Offline Browsing: CSS can store web applications locally with the help of an
offline cache. Using this we can view offline websites.
• CSS is used to define styles for your web pages, including the design, layout and
variations in display for different devices and screen sizes.
• Pages load faster − If you are using CSS, you do not need to write HTML tag attributes
every time. Just write one CSS rule of a tag and apply it to all the occurrences of that
tag. So less code means faster download times.
• Multiple Device Compatibility − Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cell phones or for
printing.
• Global web standards − Now HTML attributes are being deprecated and it is being
recommended to use CSS. So its a good idea to start using CSS in all the HTML pages
to make them compatible to future browsers.

CSS Syntax
Selector {
Property 1: value;
Property 2: value;
Property 3: value;
}

• Selector: points to the HTML element you want to style.


• There are few basic selectors like tags, id’s, and classes
• 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.
• CSS declaration always ends with a semicolon, and declaration blocks are surrounded
by curly braces.
For example:
h1 {
color:blue;
font size:12px;
}
Where, Selector -- h1
Declaration -- {color:blue; font size:12px;}

In the above example, color is property and blue is value.


font-size is property and 12px is value.
Levels of style sheets
• The three levels of style sheets, in order from lowest level to highest level, are inline,
document level, and external.
• Inline style sheets apply to the content of a single HTML element.
• Document-level style sheets apply to the whole body of a document.
• And external style sheets can apply to the bodies of any number of documents.
• Inline style sheets have precedence over document style sheets, which have precedence
over external style sheets.
• For example, if an external style sheet specifies a value for a particular property of a
particular element, that value is used until a different value is specified in either a
document style sheet or an inline style sheet.
• Likewise, document style sheet property values can be overridden by different property
values in an inline style sheet.
• In effect, the properties of a specific element are those that result from a merge of all
applicable style sheets, with lower-level style sheets having precedence in cases of
conflicting specifications.
• If no style sheet provides a value for a particular style property, the browser default
property value is used or if a particular browser is not capable of using the property
values specified in a style sheet, then the browser either would substitute an alternative
value or would simply ignore the given value and use its default value.
• Inline style specifications appear within the opening tag and apply only to the content
of that element.
• Document-level style specifications appear in the document head section and apply to
the entire body of the document. This is obviously an effective way to impose a uniform
style on the presentation of all of the content of a single document.
• In many cases, it is desirable to have a style sheet apply to more than one document.
That is the purpose of external style sheets, which are not part of any of the documents
to which they apply. They are stored separately and are referenced in all documents that
use them.
• Another advantage of external style sheets is that their use cleanly separates CSS from
HTML.
• External style sheets are written as text files with the MIME type text/css. They can be
stored on any computer on the Web.
• The browser fetches external style sheets just as it fetches HTML documents. The
<link> tag is used to specify external style sheets. Within <link>, the rel attribute is
used to specify the relationship of the linked to document to the document in which the
link appears.
• The href attribute of <link> is used to specify the URL of the style sheet document, as
in the following example:
<link rel = "stylesheet" type = "text/css"
href = "http://www.cs.usc.edu/styles/wbook.css" />

• The link to an external style sheet must appear in the head of the document. If the
external style sheet resides on the Web server computer, only its path address must be
given as the value of href.
• It is good to separate CSS from markup, it is preferable to use external style sheets.
• External style sheets can be validated with the service provided at
http://jigsaw.w3.org/css-validator/

Style Specification Formats


The format of a style specification depends on the level of style sheet.

CSS can be added to HTML documents in 3 ways:


• Inline - by using the style attribute inside HTML elements
• Internal - by using a <style> element in the <head> section
• External - by using a <link> element to link to an external CSS file

Inline CSS: Inline CSS contains the CSS property in the body section attached with element
is known as inline CSS. Inline style specifications appear as values of the style attribute of a
tag, the general form of which is as follows:
style = "property_1 : value_1; property_2 : value_2; ...;
property_n : value_n;"
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>

<body>
<p style = "color:#009900; font-size:50px;
font-style:italic; text-align:center;"> BMS College of Engineering
</p>

</body>
</html>

Internal or Embedded CSS or Document Style: This can be used when a single HTML
document must be styled uniquely. It appears as the content of a style element within the
header of a document. The general form of the content of a style element is as follows:
<style type = "text/css">
rule_list
</style>
The type attribute of the <style> tag tells the browser the type of style specification, which is
text/css for CSS.
Each style rule in a rule list has two parts: a selector, which indicates the element or elements
affected by the rule, and a list of property-value pairs.
The form of a style rule is as follows:
selector {property_1 : value_1; property_2 : value_2; ...;
property_n:value_n;}
If a property is given more than one value, those values usually are separated with spaces. For
some properties, however, multiple values are separated with commas.
Note: CSS comments are introduced with /* and terminated with */. HTML comments
cannot be used in CSS.

Example:
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

External CSS: An external style sheet consists of a list of style rules of the same form as in
document style sheets. The <style> tag is not included. External CSS contains separate CSS
file which contains only style property with the help of tag attributes (For example class, id,
heading, … etc). CSS property written in a separate file with .css extension and should be
linked to the HTML document using link tag. This means that for each element, style can be
set only once and that will be applied across web pages.
Example:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

The external style sheet can be written in any text editor. The file must not contain any HTML
code, and must be saved with a .css extension.

Example: "styles.css":
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p{
color: red;
}

Content delivery network (CDN)


• A content delivery network (CDN) refers to a geographically distributed group of
servers which work together to provide fast delivery of Internet content.
• A CDN allows for the quick transfer of assets needed for loading Internet content
including HTML pages, javascript files, stylesheets, images, and videos.
• Data centers across the globe use caching, a process that temporarily stores copies of
files, so that you can access internet content from a web-enabled device or browser
more quickly through a server near you.
• CDNs cache content like web pages, images, and video in proxy servers near to your
physical location. This allows you to do things like watch a movie, download software,
check your bank balance, post on social media, or make purchases, without having to
wait for content to load.
• CDN services were created to solve the problem of network congestion caused by
delivering rich web content, such as graphics and video over the internet — much like
a traffic jam.
• Getting content from centrally located servers to individual users simply took too long.
CDNs have now grown to include everything from text, graphics, scripts, and media
files to software downloads, documents, portals, ecommerce, live streaming media, on-
demand video streaming media, and social media sites.
• The popularity of CDN services continues to grow, and today the majority of web traffic
is served through CDNs, including traffic from major sites like Facebook, Netflix, and
Amazon.
• A properly configured CDN may also help protect websites against some common
malicious attacks, such as Distributed Denial of Service (DDOS) attacks.

What is an example of a CDN?


A large portion of all internet content is delivered through CDNs. Here is a simple example:
If you were in New York and wanted to view the website of your favorite store in London
that’s hosted on a server in the UK, you would experience slow content load times if the request
had to travel all the way across the Atlantic Ocean. To remedy this, a CDN would store a cached
version of the London website content in multiple geographical locations around the world,
also called “points of presence” (PoPs). These PoPs contain their own caching servers and are
responsible for delivering that content close to where you’re located in New York.
Content delivered from a server closest to your physical location gives you a faster, high-
performance web experience.
What are the benefits of using a CDN?
Although the benefits of using a CDN vary depending on the size and needs of an Internet
property, the primary benefits for most users can be broken down into 4 different components:
1. Improving website load times - By distributing content closer to website visitors by using
a nearby CDN server (among other optimizations), visitors experience faster page loading
times. As visitors are more inclined to click away from a slow-loading site, a CDN can
reduce bounce rates and increase the amount of time that people spend on the site. In other
words, a faster a website means more visitors will stay and stick around longer.
2. Reducing bandwidth costs - Bandwidth consumption costs for website hosting is a
primary expense for websites. Through caching and other optimizations, CDNs are able to
reduce the amount of data an origin server must provide, thus reducing hosting costs for
website owners.
3. Increasing content availability and redundancy - Large amounts of traffic or hardware
failures can interrupt normal website function. Thanks to their distributed nature, a CDN
can handle more traffic and withstand hardware failure better than many origin servers.
4. Improving website security - A CDN may improve security by providing DDoS
mitigation, improvements to security certificates, and other optimizations.

How does a CDN work?


At its core, a CDN is a network of servers linked together with the goal of delivering content
as quickly, cheaply, reliably, and securely as possible. In order to improve speed and
connectivity, a CDN will place servers at the exchange points between different networks.

These Internet exchange points (IXPs) are the primary locations where different Internet
providers connect in order to provide each other access to traffic originating on their different
networks. By having a connection to these high speed and highly interconnected locations, a
CDN provider is able to reduce costs and transit times in high speed data delivery.

Is a CDN the same as a web host?


While a CDN does not host content and can’t replace the need for proper web hosting, it does
help cache content at the network edge, which improves website performance. Many websites
struggle to have their performance needs met by traditional hosting services, which is why they
opt for CDNs.
By utilizing caching to reduce hosting bandwidth, helping to prevent interruptions in service,
and improving security, CDNs are a popular choice to relieve some of the major pain points
that come with traditional web hosting.

Selector Forms
A selector specifies the elements to which the following style information applies.
The selector can have a variety of forms.

Simple Selector Forms

The simplest selector form is a single element name, such as h1. In this case, the property
values in the rule apply to all occurrences of the named element. The selector could be a list of
element names separated by commas, in which case the property values apply to all occurrences
of all of the named elements. Consider the following examples:

h1 {property-value list}
h2, h3 {property-value list}

The first of these selector forms specifies that the following property-value list applies to all
h1 elements. The second specifies that the following property-value list applies to all h2 and
h3 elements.

The Universal Selector

The universal selector, denoted by an asterisk (*), applies its style to all elements in a
document. For example, if we wanted every element in a document to have a particular set of
properties, we could include the following:
* {property-value list}

Class Selectors

Class selectors are used to allow different occurrences of the same tag to use different style
specifications. A style class is defined in a style element by giving the style class a name,
which is attached to the tag’s name with a period. For example, if you want two paragraph
styles in a document—say, normal and
warning—you could define these two classes in the content of a style element as follows:
p.normal {property-value list}
p.warning {property-value list}
Within the document body, the particular style class that you want is specified with the class
attribute of the affected tag—in the preceding example, the paragraph tag. For example, you
might have the following markup:
<p class = "normal">
A paragraph of text that we want to be presented in
'normal' presentation style
</p>
<p class = "warning">
A paragraph of text that is a warning to the reader, which
should be presented in an especially noticeable style
</p>

id Selectors
An id selector allows the application of a style to one specific element. The general form of
an id selector is as follows:
#specific-id {property-value list}
As you would probably guess, the style specified in the id selector applies to the element with
the given id. For example, consider the following selector:
#section14 {property-value list}
Following is the h2 element to which this style applies:
<h2 id = "section14"> 1.4 Calico Cats </h2>

Pseudo Classes

Pseudo classes specify that certain styles apply when something happens, rather than because
the target element simply exists. In this section, we describe and illustrate four pseudo
classes, two that are used exclusively to style hypertext links, and two that can be used to
style any element.
The two pseudo classes for styling links are link and visited. The link pseudo class is used to
style a link that has not been selected; visited is used to style a link that previously has been
selected.

The style of the hover pseudo class applies when its associated element has the mouse cursor
over it. The style of the focus pseudo class applies when its associated element has focus.

Browsers often use blue as the default color for unvisited links and red or purple for visited
links. They usually also underline links. If the background color is white, this is fine.
However, if the background color is not white, it is better to make the unvisited links some
bright color that contrasts with the background
color of the document. Contrasting colors can be found with a color sphere, such as can be
found at http://www.colorjack.com/sphere. In such a sphere, contrasting colors are 180
degrees apart on the sphere. Visited links can then be a muted version of the chosen
contrasting color.

When using the hover pseudo class, changing the size of an element from its initial size, for
example by enlarging or shrinking the font size, can lead to problems. For example, if the
font size is made larger, the larger size could cause the element to overflow the area reserved
for it in the display, causing the whole document to be rearranged. That would likely annoy
the user.

Whereas the names of style classes and generic classes begin with a period, the names of
pseudo classes begin with a colon. For example, the selector for the hover pseudo class
applied to an h2 element is as follows:
h2:hover {property-value list}
Any time the mouse cursor is positioned over an h2 element, the styles defined in the given
property-value list are applied to the content of the h2 element.

Pseudo-elements
A pseudo-class can be defined as a keyword which is combined to a selector that defines the
special state of the selected elements. Unlike the pseudo-classes, the pseudo-elements are used
to style the specific part of an element, whereas the pseudo-classes are used to style the element.
As an example, a pseudo-element can be used to style the first letter or the first line of an
element. The pseudo-elements can also be used to insert the content after or before an element.

Syntax
Pseudo-element has a simple syntax which is given as follows:
1. selector::pseudo-element {
2. property: value;
3. }

All CSS Pseudo Elements

Selector Example Example description

::after p::after Insert something after the content of each <p> element

::before p::before Insert something before the content of each <p> element

::first-letter p::first-letter Selects the first letter of each <p> element

::first-line p::first-line Selects the first line of each <p> element

::marker ::marker Selects the markers of list items

::selection p::selection Selects the portion of an element that is selected

The ::first-letter pseudo-element


As its name implies, it affects the first letter of the text. It can be applied only to block-level
elements. Instead of supporting all CSS properties, it supports some of the CSS properties that
are given below.
o Color properties (such as color)
o Font properties (such as font-style, font-family, font-size, font-color, and many
more).
o Margin properties (such as margin-top, margin-right, margin-bottom, and margin-
left).
o Border properties (like border-top, border-right, border-bottom, border-left,
border-color, border-width, and many more).
o Padding properties (such as padding-top, padding-right, padding-bottom, and
padding-left).
o Background properties (such as background-color, background-repeat,
background-image, and background-position).
o Text related properties (such as text-shadow, text-transform, text-decoration, etc.).
o Other properties are vertical-align (only when the float is 'none') wo
Example
<html>
<head>
<style>
body{
text-align: center;
}
h1::first-letter {
font-family: Lucida Calligraphy;
font-size: 3cm;
color: red;
text-shadow: 5px 8px 9px green;
}
h1{
color: blue;
}
</style>
</head>
<body>
<h1> Welcome to the javaTpoint.com </h1>
<h2> This is an example of ::first-letter pseudo-element. </h2>
</body>
</html>

Output
The ::first-line pseudo-element
It is similar to the ::first-letter pseudo-element, but it affects the entire line. It adds the special
effects to the first line of the text. It supports the following CSS properties:
o Color properties (such as color)
o Font properties (such as font-style, font-family, font-size, font-color, and many
more).
o Background properties (such as background-color, background-repeat,
background-image, and background-position).
o Other properties are word-spacing, letter-spacing, line-height, vertical-align, text-
transform, text-decoration.
Example
In this example we will see the use of ::first-line element to add special effects to the element's
first line.
<html>
<head>
<style>
body{
text-align: center;
}
h1::first-line {
font-family: Lucida Calligraphy;
font-size: 1cm;
color: red;
text-shadow: 5px 8px 9px green;
}
</style>
</head>
<body>
<h1> Welcome to the javaTpoint.com. This site is developed so that students may lear
n computer science related technologies easily. The javaTpoint.com is committed to provi
de easy and in-depth tutorials on various technologies. </h1>
<h2> This is an example of ::first-line pseudo-element. </h2>
</body>
</html>

Output:
The ::before pseudo-element
It allows us to add something before the element's content. It is used to add something before
the specific part of an element. Generally, it is used with the content property.
We can also add the regular strings or images before the content using this pseudo-element.
Example
<html>
<head>
<style>
body{
text-align: center;
}
h1::before {
content: "'Hello World.'";
color: red;
}
</style>
</head>
<body>
<h1>Welcome to the javaTpoint.com. </h1>
<h2> This is an example of ::before pseudo-element. </h2>
<h3> In the first line the "Hello World" has added by using the pseudo-
element ::before </h3>
</body>
</html>

Output
The ::after pseudo-element
It works similar to ::before pseudo-element, but it inserts the content after the content of the
element. It is used to add something after the specific part of an element. Generally, it is used
with the content property.
It also allows us to add regular strings or images after the content.
Example
<html>
<head>
<style>
body{
text-align: center;
}
h1::after {
content: "'Welcome to the javaTpoint.com.'";
color: red;
}
</style>
</head>
<body>
<h1> Hello World. </h1>
<h2> This is an example of ::after pseudo-element. </h2>
<h3> In the first line the "Welcome to the javaTpoint.com." has added by using the pse
udo-element ::after </h3>
</body>
</html>

Output
The ::selection pseudo-element
It is used to style the part of an element that is selected by the user. We can use the following
CSS properties with it:
o color.
o background-color.
o Other properties include cursor, outline, etc.
Example
<html>
<head>
<style>
body{
text-align: center;
}
h1::selection {
color: red;
}
</style>
</head>
<body>
<h1> Hello World. </h1>
<h2> Select the text in first line to see the effect. </h2>
<h3> This is an example of ::selection pseudo-element. </h3>
</body>
</html>

Output:
CSS classes and pseudo-element
The pseudo-elements can be combined with CSS classes to style the specific element having
that class. The syntax of combining the CSS classes with the pseudo-elements is given below.
Syntax
It can be written as:
selector.class::pseudo-element {
property: value
}
Example
This example will affect the first letter of those <h1> elements that
have class="example" rather than affecting the all <h1> elements.
<html>
<head>
<style>
body{
text-align: center;
}
h1.example::first-letter {
color: red;
font-size: 2cm;
font-family: Lucida Calligraphy;
}
</style>
</head>
<body>
<h1 class="example"> Hello World. </h1>
<h1> Welcome to the javaTpoint.com. </h1>
<h3> This is an example of pseudo-element with CSS classes.</h3>
</body>
</html>
Output

The ::marker Pseudo-element


::marker Pseudo-element selects the marker box of a list item, which typically contains a
bullet or number. It works on any element or pseudo-element set to display: list-item, such
as the <li> and <summary> elements.
Example
<!DOCTYPE html>
<html>
<head>
<style>
::marker {
color: red;
font-size: 23px;
}
</style>
</head>
<body>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

<ol>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>

</body>
</html>
Output

Multiple Pseudo-elements
Several pseudo-elements can also be combined.
In the following example, the first letter of a paragraph will be red, in an xx-large font size.
The rest of the first line will be blue, and in small-caps. The rest of the paragraph will be the
default font size and color:
Example
<!DOCTYPE html>
<html>
<head>
<style>
p::first-letter {
color: #ff0000;
font-size: xx-large;
}

p::first-line {
color: #0000ff;
font-variant: small-caps;
}
</style>
</head>
<body>

<p>You can combine the ::first-letter and ::first-line pseudo-elements to add a special effect
to the first letter and the first line of a text!</p>

</body>
</html>

Output
CSS Combinators
CSS Combinators clarifies the relationship between two selectors, whereas the selectors in CSS
are used to select the content for styling.
There can be more than one simple selector in a CSS selector, and between these selectors, we
can include a combinator. Combinators combine the selectors to provide them a useful
relationship and the position of content in the document.
There are four types of combinators in CSS that are listed as follows:
o General sibling selector (~)
o Adjacent sibling selector (+)
o Child selector (>)
o Descendant selector (space)

General Sibling Selector (~)


It uses the tlide (~) sign as the separator between the elements. It selects the elements that
follow the elements of first selector, and both of them are the children of the same parent. It
can be used for selecting the group of elements that share the common parent element.
It is useful when we have to select the siblings of an element even if they are not adjacent
directly.
Syntax
element ~ element {
/*style properties*/
}
Suppose we have to select all <p> elements that are the siblings of <div> element, then we can
write it as:
1. div ~ p {
2. /*style properties*/
3. }
The figure given below helps us to understand the General sibling selector (~).
In this figure, the blocks with the green color are the selected blocks affected after using the
general sibling selector.

Example
In this example we are selecting the <p> elements that come after the <h1>. There is
a <div> element which will not get selected and the paragraph element inside the div will also
not get selected. But those <p> elements that come after the <div> will be affected.
<!DOCTYPE html>
<html>
<head>
<title>General Sibling Selector</title>
<style>
body{
text-align: center;
}
h1 ~ p{
color: blue;
font-size: 25px;
font-weight: bold;
text-align: center;
}
div {
font-size: 32px;
}
</style>
</head>

<body>
<h1>General sibling selector (~) property</h1>
<p>It is the first paragraph element which will get effected.</p>
<div> It is the div element
<p> It is the paragraph under the div element </p>
</div>
<p>It is the paragraph element after the div</p>
<p>It is the paragraph element which will also get affected</p>
</body>
</html>

Output

Adjacent Sibling Selector (+)


It uses the plus (+) sign as the separator between the elements. It matches the second element
only when the element immediately follows the first element, and both of them are the children
of the same parent. This sibling selector selects the adjacent element, or we can say that the
element which is next to the specified tag.
It only selects the element which is just next to the specified first element.
Syntax
element + element {
/*style properties*/
}

If we have to select the paragraph that comes immediately after another paragraph, then by
using the adjacent selector, it will be written as follows:
p+p{
/*style properties*/
}

The figure given below helps us to understand the Adjacent sibling selector (+).
In this figure, the blocks with the green color are the selected blocks affected after using the
adjacent sibling selector. There is the selection of those paragraph elements that immediately
comes after another paragraph element.
Example
In this example we are selecting the <p> element that comes immediately after
the <p> element. There is an <div> element that will not be selected, and the paragraph
element after the div will also not be selected. But the <p> element that comes just next to the
third paragraph will be affected.
<!DOCTYPE html>
<html>
<head>
<title> Adjacent Sibling Selector </title>
<style>
body{
text-align: center;
}
p + p{
color: Blue;
font-size:25px;
font-weight: bold;
text-align: center;
}
p{
font-size: 32px;
}
</style>
</head>

<body>
<h1> Adjacent sibling selector (+) property</h1>
<p> It is the first paragraph </p>
<p> It is the second paragraph which is immediately next to the first paragraph, and it get
selected. </p>
<div> This is the div element </div>
<p> This is the third paragraph which does not get affected </p>
<p> This paragraph is also selected because it immediately next to third paragraph </p>
</body>
</html>

Output

Child Selector (>)


It uses the greater than (>) sign as the separator between the elements. It selects the direct
descendant of the parent. This combinator only matches the elements that are the immediate
child in the document tree. It is stricter as compared to the descendant selector because it selects
the second selector only when the first selector is its parent.
The parent element must always be placed at the left of the ">". If we remove the greater
than (>) symbol that designates this as a child combinator, then it will become the descendant
selector.
Syntax
element > element {
/*style properties*/
}
If we have to select the paragraph elements that are the children of <div> element then by using
the child selector, it will be written as follows:
div > p {
/*style properties*/
}

The figure given below helps us to understand the child selector (>).
In this figure, the blocks with the green color are the selected blocks affected after using the
child selector. As we can see in the figure, there is only the selection of those paragraph
elements that are the direct child of the div element.
Example
In this example we are selecting the <p> elements that are the child of a <div> element. It only
selects those paragraph elements that are the direct child of the div element.
<!DOCTYPE html>
<html>
<head>
<title> Child Selector </title>
<style>
body{
text-align: center;
}

div > p{
color: Blue;
font-size:25px;
font-weight:bold;
text-align:center;
}
p{
font-size: 20px;
}

</style>
</head>

<body>
<h1> Child selector (>) property</h1>
<p> It is the first paragraph </p>
<p> It is the second paragraph </p>
<div>
<h1>This is the div element</h1>
<p> This is the third paragraph which is the child of div element </p>
<p> This is the fourth paragraph and also get selected because it is also the child of div el
ement </p>
</div>
</body>
</html>

Output

Descendant Selector (space)


It uses the space as the separator between the elements. The CSS descendant selector is used
to match the descendant elements of a particular element and represent it using a single space.
The word descendant indicates nested anywhere in the DOM tree. It can be a direct child or
deeper than five levels, but it will still be referred to as a descendant.
It combines two selectors in which the first selector represents an ancestor (parent, parent's
parent, etc.), and the second selector represents descendants. The elements matched by the
second selector are selected if they have an ancestor element that matches the first selector.
Syntax
element element {

/*style properties*/
}
If we have to select the paragraph elements that are the children of an <div> element, then by
using the descendant selector, it will be written as follows:
div p {
/*style properties*/
}
The figure given below helps us to understand the descendant selector.

Example:

<!DOCTYPE html>
<html>
<head>
<title> Descendant Selector </title>
<style>
body{
text-align: center;
}
div p{
color: blue;
font-size:28px;
font-weight: bold;
text-align: center;
}
p,div {
font-size: 25px;
}

</style>
</head>

<body>
<div>
<p> This is 1st paragraph in the div. </p>
<p> This is 2nd paragraph in the div. </p>
<span>
This is the span element in the div
<p> This is the paragraph in the span. It will also be affected. </p>
</span>
</div>

<p> Paragraph 4. It will not be affected because it is not in the div. </p>

</body>
</html>
Output

The CSS box model


The CSS box model is a container that contains multiple properties including borders,
margin, padding, and the content itself. It is used to create the design and layout of web pages.
It can be used as a toolkit for customizing the layout of different elements. The web browser
renders every element as a rectangular box according to the CSS box model.
The following diagram illustrates how the CSS properties of width, height, padding, border
and margin dictate that how much space an attribute will occupy on a web page.
Box-Model has multiple properties in CSS. They are as mentioned below:
• content: This property is used to displays the text, images, etc, that can be sized using
the width & height property.
• padding: The padding area is the space around the content area and within the border-
box. It can be applied to all sides of the box or to the specific, selected side(s) - top, right,
bottom, and/or left.
• border: The border area surrounds the padding and the content, and can be applied to
all the sides of the box or to selected side(s) - top, right, bottom, and/or left. It also allows
to set the style, color, and width of the border.
• margin: The margin area consists of space between the border and the margin. The
margin does not possess its own background color and is completely transparent. It
shows the background color of the element, like the body element.

Borders
Every element has a property, border-style, that controls whether the element’s content has a
border, and also specifies the style of the border. CSS provides several different border styles,
among them dotted, dashed, solid, and double. The default value for border-style is none, which
is why the contents of elements normally do not have borders. The styles of one particular side
of an element can be set with border-top-style, border-bottom-style, border-left-style, or
border-right-style.

The border-width property is used to specify the thickness of a border. Its possible values are
thin, medium (the default), thick, or a length value, which is in pixels. Setting border-width
sets the thickness of all four sides of an element. The width of one particular border of an
element can be specified with border-top-width, border-bottom-width, border-left-width, or
border-right-width.
The color of a border is controlled by the border-color property. Once again, the individual
borders of an element can be colored differently through the properties border-top-color,
border-bottom-color, border-leftcolor, or border-right-color.

There is a shorthand for setting the style properties of all four borders of an element, border.
For example, we could have the following: border: 5px solid blue;

This is equivalent to the following:


border_width: 5px; border-style: solid; border-color: blue;

The cells of a table can have borders, like any other element. We could specify borders on the
cells with the following:
td, th {border: thin solid black;}

In many cases, we want just one border between table cells, rather than the default double
borders that result from this specification (for example, the right border of a cell and the left
border of its neighbor cell to the right together form a double border). To get just one border
between table cells, we set the table property border-collapse to collapse (its default value is
separate).

The following document, borders.html, illustrates borders, using a table and a short paragraph
as examples:

<!-- borders.html Examples of various borders -->


<html lang = "en">
<head>
<title> Borders </title>
<meta charset = "utf-8" />
<style type = "text/css">
td, th {border: thin solid black;}
table {border: thin solid black;
border-collapse: collapse;
border-top-width: medium;
border-bottom-width: thick;
border-top-color: red;
border-bottom-color: blue;
border-top-style: dotted;
border-bottom-style: dashed;
}
p {border: thin dashed green;}
</style>
</head>
<body>
<table>
<caption> Fruit Juice Drinks </caption>
<tr>
<th> </th>
<th> Apple </th>
<th> Orange </th>
<th> Screwdriver </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
<td> 0 </td>
</tr>
<tr>
<th> Dinner </th>
<td> 0 </td>
<td> 0 </td>
<td> 1 </td>
</tr>
</table>
<p>
Now is the time for all good Web developers to learn to use style sheets.
</p>
</body>
</html>

Output:

Notice that if a table has borders that were specified with its border or border-style attribute, as
well as border properties that are specified for one particular border, as in borders.html, those
for the particular border override those of the original border. In borders.html, the table element
uses its border attribute to set the border to thin, but the top and bottom borders are replaced
by those specified with the border-top and border-bottom properties.

Margins and Padding

Padding is the space between the content of an element and its border. The margin is the space
between the border of an element and the element’s neighbors. When there is no border, the
margin plus the padding is the space between the content of an element and its neighbors. In
this scenario, it may appear that there is no difference between padding and margins. However,
there is a difference when the element has a background: The background extends into the
padding, but not into the margin.

The margin properties are named margin, which applies to all four sides of an element, margin-
left, margin-right, margin-top, and margin-bottom. The padding properties are named padding,
which applies to all four sides, padding-left, padding-right, padding-top, and padding-bottom.

The following example, marpads.html, illustrates several combinations of margins and


padding, both with and without borders:

<!DOCTYPE html>
<!-- marpads.html An example to illustrate margins and padding -->
<html lang = "en">
<head>
<title> Margins and Padding </title>
<meta charset = "utf-8" />
<style type = "text/css">
p.one {margin: 15px;
padding: 15px;
background-color: #C0C0C0;
border-style: solid;
}
p.two {margin: 5px;
padding: 25px;
background-color: #C0C0C0;
border-style: solid;
}
p.three {margin: 25px;
padding: 5px;
background-color: #C0C0C0;
border-style: solid;
}
p.four {margin: 25px;
background-color: #C0C0C0;}
p.five {padding: 25px;
background-color: #C0C0C0;
}
</style>
</head>
<body>
<p> Here is the first line. </p>
<p class = "one">
Now is the time for all good Web programmers to learn to use style sheets. <br />
[margin = 15px, padding = 15px]
</p>
<p class = "two">
Now is the time for all good Web programmers to learn to use style sheets. <br />
[margin = 5px, padding = 25px]
</p>
<p class = "three">
Now is the time for all good Web programmers to learn to use style sheets. <br />
[margin = 25px, padding = 5px]
</p>
<p class = "four">
Now is the time for all good Web programmers to learn to use style sheets. <br />
[margin = 25px, no padding, no border]
</p>
<p class = "five">
Now is the time for all good Web programmers to learn to use style sheets. <br />
[padding = 25px, no margin, no border]
</p>
<p> Here is the last line. </p>
</body>
</html>

Output:

Property-Value Forms

CSS includes a large number of different properties, arranged in categories. The most
commonly used categories are: fonts, lists, alignment of text, margins, colors, backgrounds,
and borders. The complete details of all properties and property values can be found at
http://www.w3.org/TR/2011/RECCSS2-20110607/propidx. html.
Property values can appear in a variety of forms. Keyword property values are used when
there are only a few possible values and they are predefined—for example, large, medium, and
small. Keyword values are not case sensitive, so Small, SmAlL, and SMALL are all the same
as small.

Number values are used when no meaningful units can be attached to a numeric property
value. A number value can be either an integer or a sequence of digits with a decimal point and
can be preceded by a sign (+ or -).

Length values are specified as number values that are followed immediately by a two-
character abbreviation of a unit name. There can be no space between the number and the unit
name. The possible unit names are px, for pixels; in, for inches; cm, for centimeters; mm, for
millimeters; pt, for points (a point is 1/72 inch); and pc, for picas, which are 12 points. Note
that on a display, in, cm, mm, pt, and pc are approximate measures. Their actual values depend
on the screen resolution. There are also two relative length values: em, which is the value of
the current font size in pixels, and ex, which is the height of the letter x.

Percentage values are used to provide a measure that is relative to the previously used measure
for a property value. Percentage values are numbers that are followed immediately by a percent
sign (%). For example, if the font size were set to 75% with a style sheet, it would make the
new current size for the font 75 percent of its previous value. Font size would stay at the new
value until changed again. Percentage values can be signed. If preceded by a plus sign, the
percentage is added to the previous value; if negative, the percentage is subtracted.

URL property values use a form that is slightly different from references to URLs in links.
The actual URL, which can be either absolute or relative, is placed in parentheses and preceded
by url, as in the following property: url(tetons.jpg).
There can be no space between url and the left parenthesis. If there is one, the property and its
value will be ignored by the browser.

Color property values can be specified as color names, as six-digit hexadecimal numbers, or
in RGB form. RGB form is just the word rgb followed by a parenthesized list of three decimal
numbers in the range of 0 to 255 or three percentage values. These numbers or percentages
specify the levels of red, green, and blue, respectively. For example, a value of 0 or 0% as the
first of the three values would specify that no red be included in the color. A value of 255 or
100% would specify the maximum amount of red. Hexadecimal numbers must be preceded
with pound signs (#), as in #43AF00. For example, fuchsia (a mixture of red and blue) could
be specified with
fuchsia
or
rgb(255, 0, 255)
or
#FF00FF
As is the case with url, there can be no space between rgb and the left parenthesis. If there is,
the value will be ignored by the browser.

Many property values are inherited by descendent elements. For example, because font-size
is an inherited property, setting it to a value on the <body> tag effectively sets that value as the
new default property value all of the elements for the whole body of the document (because all
elements in the body of a document are descendants of the body element).

Not all properties are inherited. For example, background-color and the margin properties are
not inherited.

Font Properties

CSS Font property is used to control the look of texts. By the use of CSS font property you can
change the text size, color, style and more.

These are some important font attributes:

1. CSS Font color: This property is used to change the color of the text. (standalone
attribute)
2. CSS Font family: This property is used to change the face of the font.
3. CSS Font size: This property is used to increase or decrease the size of the font.
4. CSS Font style: This property is used to make the font bold, italic or oblique.
5. CSS Font variant: This property creates a small-caps effect.
6. CSS Font weight: This property is used to increase or decrease the boldness and
lightness of the font.

Font Color

The color property is used to set the color of the text. The color is specified by:
• a color name - like "red"
• a HEX value - like "#ff0000"
• an RGB value - like "rgb(255,0,0)"

Example Program:

<!DOCTYPE html>
<html>
<head>
<style>
body {
color: blue;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>This is heading 1</h1>
<p>This is an ordinary paragraph. Notice that this text is blue. The default text color
for a page is defined in the body selector.</p>
<p>Another paragraph.</p>
</body>
</html>

Output:

Font Families
The font-family property is used to specify a list of font names. The browser uses the first
font in the list that it supports. For example, the following property:
font-family: Arial, Helvetica, Futura
tells the browser to use Arial if it supports that font. If it does not support Ariel, it should
use Helvetica if it supports it. If the browser supports neither Arial nor Helvetica, it should
use Futura if it supports it. If the browser does not support any of the specified fonts, it will
use an alternative of its choosing.

A generic font can be specified as a font-family value. The possible generic fonts and
examples of each are shown in Table 1. Every browser has a font defined for each of these
generic names. A good approach to specifying fonts is to use a generic font as the last font
in the value of a font-family property. For example, because Arial, Helvetica, and Futura
are sans-serif fonts, the previous example would be better as follows:

Table 1 Generic fonts


Generic Name Examples
serif Times New Roman, Garamond
sans-serif Arial, Helvetica
cursive Caflisch Script, Zapf-Chancery
fantasy Critter, Cottonwood
monospace Courier, Prestige

font-family: Arial, Helvetica, Futura, sans-serif

Now, if the browser does not support any of the named fonts, it will use a font from the same
category, in this case, sans serif.

If a font name has more than one word, the whole name should be delimited by single quotes,
as in the following example: font-family: 'Times New Roman'

In practice, the quotes may not be required, but their use is recommended.

Font Sizes
The font-size property does what its name implies its value specifies the size of the font.
Unfortunately, it is not as simple as we wish it were.

There are two categories of font-size values, absolute and relative. In the absolute category, the
size value could be given as a length value in points, picas, or pixels, or as a keyword from the
list: xx-small, x-small, small, medium, large, x-large, and xx-large. One problem with the
keyword sizes is that the size relationship between adjacent keywords is not exactly the same
on different browsers.

The relative size values are smaller and larger, which adjust the font size relative to the font
size of the parent element. Once again, however, the amount of change that results from these
is not the same among browsers. Percent values can also be used to adjust the font size relative
to the font size of the parent element. But in this case, the property value is a uniform size
adjustment. Finally, a number with the unit em can be used. For example, font-size: 1.2em

This sets the font size to 1.2 times the font size of the parent element. So, percentages and the
use of em are equivalent. 1.2em and 120% are exactly the same.

One problem with using points and picas for font sizes is that they do not display in the same
size on different computers. Points and picas were designed for printed media—that is where
they should be used. Furthermore, if the user changes the default font size, on some browsers
these will not change. If a relative size is given, the font size will be scaled relative to a new
default set by the user. Although the keywords are in the absolute category, they are set relative
to the default font size of the browser.

Considering all of these issues, percentages and em are good choices for setting font sizes.

Font Variants
The default value of the font-variant property is normal, which specifies the usual character
font. This property can be set to small-caps to specify small capital letters. These are all
uppercase, but the letters that are normally uppercase are a bit larger than those that are
normally lowercase.

Font Styles
The font-style property is usually used to specify italic, as in font-style: italic

An alternative to italic is oblique, but when displayed, the two are nearly identical, so oblique
is not a terribly useful font style.

There is one other possible value for font-style, normal, which specifies that the font be the
normal style. This tells the browser to stop using whatever non-normal style it had been using
until instructed otherwise.

Font Weights
The font-weight property is used to specify the degree of boldness, as in font-weight: bold

Besides bold, the possible values normal (the default), bolder, and lighter can be specified. The
bolder and lighter values are taken as relative to the level of boldness of the parent element.
Specific numbers also can be given in multiples of 100 from 100 to 900, where 400 is the same
as normal and 700 is the same as bold. Because many fonts are available only in normal and
bold, the use of these numbers often just causes the browser to choose either normal or bold.

Font Shorthands
If more than one font property must be specified, the values can be stated in a list as the value
of the font property. The browser then determines which properties to assign from the forms
of the values. For example, the property font: bold 1.1em 'Times New Roman' Palatino
specifies that the font weight should be bold, the font size should be 1.1 times that of its parent
element, and either Times New Roman or Palatino font should be used, with precedence given
to Times New Roman.

The order in which the property values are given in a font value list is important. The order
must be as follows: The font names must be last, the font size must be second to last, and the
font style, font variant, and font weight, when they are included, can be in any order but must
precede the font size. Only the font size and the font family are required in the font value list.

Example Program:

<!DOCTYPE html>
<!-- fonts.html An example to illustrate font properties -->
<html lang = "en">
<head>
<title> Font properties </title>
<meta charset = "utf-8" />
<style type = "text/css">
p.major {font-size: 1.1em;
font-style: italic;
font-family: 'Times New Roman';
}
p.minor {font: 0.9em bold 'Courier New';}
h2 {font-family: 'Times New Roman';
font-size: 2em; font-weight: bold;}
h3 {font-family: 'Courier New'; font-size: 1.5em;}
</style>
</head>
<body>
<p class = "major">
If a job is worth doing, it's worth doing right.
</p>
<p class = "minor">
Two wrongs don't make a right, but they certainly can get you in a lot of trouble.
</p>
<h2> Chapter 1 Introduction </h2>
<h3> 1.1 The Basics of Computer Networks </h3>
</body>
</html>

Output:
Text Decoration
The text-decoration property is used to specify some special features of text. The available
values are line-through, overline, underline, and none, which is the default. Many browsers
implicitly underline links. The none value can be used to avoid this underlining. Note that text-
decoration is not inherited. The following document, decoration.html, illustrates the
linethrough, overline, and underline values:

<!DOCTYPE html>
<!-- decoration.html An example that illustrates several of the possible text decoration values
-->
<html lang = "en">
<head>
<title> Text decoration </title>
<meta charset = "utf-8" />
<style type = "text/css">
p.delete {text-decoration: line-through;}
p.cap {text-decoration: overline;}
p.attention {text-decoration: underline;}
</style>
</head>
<body>
<p class = "delete">
This illustrates line-through
</p>
<p class= "cap">
This illustrates overline
</p>
<p class = "attention">
This illustrates underline
</p>
</body>
</html>

Output:
Text Spacing
The letter-spacing property controls the amount of space between the letters in words. This
spacing is called tracking. The possible values of letterspacing are normal or any length
property value. Positive values increase the letter spacing; negative values decrease it. For
example, letter-spacing: 1px spreads the letters of words. Likewise, letter-spacing: -1px
squeezes the letters of words together. The value normal resets letter-spacing back to that of
the parent element.

The space between words in text can be controlled with the word-spacing property, whose
values are normal or any length value. Once again, a positive value increases the space between
words and negative values decrease that space and normal resets word-spacing back to that of
the parent element.

The space between lines of text can be controlled with the line-height property. This spacing
is called leading. The value of line-height can be a number, in which case a positive number
sets the line spacing to that number times the font size (2.0 means double spacing). The value
could be a length, such as 24px. If the font size is 12 pixels, this would specify double spacing.
The value could be a percentage, which is relative to the spacing of the parent element.

Finally, normal, which overrides the current value, is used to set line spacing back to that of
the parent element.

The following document, text_space.html, illustrates the text spacing properties:

<!DOCTYPE html>
<!-- text_space.html An example to illustrate text spacing properties -->
<html lang = "en">
<head>
<title> Text spacing properties </title>
<meta charset = "utf-8" />
<style type = "text/css">
p.big_tracking {letter-spacing: 0.4em;}
p.small_tracking {letter-spacing: -0.08em;}
p.big_between_words {word-spacing: 0.4em;}
p.small_between_words {word-spacing: -0.1em;}
p.big_leading {line-height: 2.5;}
p.small_leading {line-height: 1.0;}
</style>
</head>
<body>
<p class = "big_tracking">
On the plains of hesitation [letter-spacing: 0.4em]
</p>
<p class = "small_tracking">
Bleach the bones of countless millions [letterspacing:-0.08em]
</p> <br />
<p class = "big_between_words">
Who at the dawn of victory [word-spacing: 0.4em]
</p>
<p class = "small_between_words">
Sat down to wait and waiting died [word-spacing: -0.1em]
</p> <br />
<p class = "big_leading">
If you think CSS is simple, [line-height: 2.5] <br />
You are quite mistaken
</p> <br />
<p class = "small_leading">
If you think HTML5 is all old stuff, [line-height:1.0] <br />
You are quite mistaken
</p>
</body>
</html>

Alignment of Text

The text-indent property can be used to indent the first line of a paragraph. This property
takes either a length or a percentage value, as in the following markup:

<style type = "text/css">


p.indent {text-indent: 2em}
</style>
...
<p class = "indent">
Now is the time for all good Web developers to begin using cascading style sheets for all
presentation details in their documents. No more deprecated tags and attributes, just nice,
precise style sheets.
</p>

This paragraph would be displayed as shown in Figure below.

The text-align property in CSS is used for the alignment of text. This CSS property is used to
set the horizontal alignment of a table-cell box or the block element. It is similar to the vertical-
align property but in the horizontal direction.

The text-align property includes values like justify, center, right, left, initial, and inherit. It
specifies the horizontal alignment of text in an element. The default value for text-align is left.

Syntax
text-align: justify | center | left | right | initial |inherit;

Property Values
Value Description

left Aligns the text to the left

right Aligns the text to the right

center Centers the text

justify Stretches the lines so that each line has equal width
(like in newspapers and magazines)

initial Sets this property to its default value.

inherit Inherits this property from its parent element.

Example Program:

<!DOCTYPE html>
<html>
<head>
<title>text-align property</title>
<style>
h1 {
color: green;
}

.main {
border: 1px solid black;
}

.gfg1 {
text-align: left;
}

.gfg2 {
text-align: right;
}

.gfg3 {
text-align: center;
}

.gfg4 {
text-align: justify;
}
</style>
</head>

<body>
<h2>text-align property</h2>
<div class="main">
<h3>text-align: left;</h3>
<div class="gfg1">
The course is designed for students as well as working professionals to
prepare for coding interviews.
</div>
</div>
<br>
<div class="main">
<h3 style="text-align: right;">text-align: right;</h3>
<div class="gfg2">
The course is designed for students as well as working professionals to
prepare for coding interviews.
</div>
</div>
<br>
<div class="main">
<h3 style="text-align: center;">text-align: center;</h3>
<div class="gfg3">
The course is designed for students as well as working professionals to
prepare for coding interviews.
</div>
</div>
<br>
<div class="main">
<h3 style="text-align: justify;">text-align: justify;</h3>
<div class="gfg4">
The course is designed for students as well as working professionals to
prepare for coding interviews.
</div>
</div>
</body>
</html>

The float property is used to specify that text should flow around some element, often an image
or a table. The possible values for float are left, right, and none, which is the default. For
example, suppose we want an image to be on the right side of the display and have text flow
around the left side of the image. To specify this condition, the float property of the image is
set to right. Because the default value for text-align is left, text-align need not be set for the
text. In the following example, the text of a paragraph is specified to flow to the left of an image
until the bottom of the image is reached, at which point the paragraph text flows across the
whole window:

<!DOCTYPE html>
<!-- float.html An example to illustrate the float property -->
<html lang = "en">
<head>
<title> The float property </title>
<meta charset = "utf-8" />
<style type = "text/css">
img {float: right;}
</style>
</head>
<body>
<p>
<img src = "c210new.jpg" alt = "Picture of a Cessna 210" />
</p>
<p>
This is a picture of a Cessna 210. The 210 is the flagship single-engine Cessna
aircraft. Although the 210 began as a four-place aircraft, it soon acquired a third row
of seats, stretching it to a six-place plane. The 210 is classified as a high-performance
airplane, which means its landing gear is retractable and its engine has more than 200
horsepower. In its first model year, which was 1960, the 210 was powered by a 260-
horsepower fuel-injected six-cylinder engine that displaced 471 cubic inches.
The 210 is the fastest single-engine airplane ever built by Cessna.
</p>
</body>
</html>

When rendered by a browser, float.html might appear as shown in figure below, depending
on the width of the browser display window.
Color

The color property in CSS is used to set the color of HTML elements. Typically, this property
is used to set the background color or the font color of an element.

In CSS, we use color values for specifying the color. We can also use this property for the
border-color and other decorative effects.

We can define the color of an element by using the following ways:


o RGB format.
o RGBA format.
o Hexadecimal notation.
o HSL.
o HSLA.
o Built-in color.

RGB Format
RGB format is the short form of 'RED GREEN and BLUE' that is used for defining the color
of an HTML element simply by specifying the values of R, G, B that are in the range of 0 to
255.
The color values in this format are specified by using the rgb() property. This property allows
three values that can either be in percentage or integer (range from 0 to 255).

Syntax
color: rgb(R, G, B);

RGBA Format
It is almost similar to RGB format except that RGBA contains A (Alpha) that specifies the
element's transparency. The value of alpha is in the range 0.0 to 1.0, in which 0.0 is for fully
transparent, and 1.0 is for not transparent.

Syntax
color:rgba(R, G, B, A);
Hexadecimal notation
Hexadecimal can be defined as a six-digit color representation. This notation starts with the #
symbol followed by six characters ranges from 0 to F. In hexadecimal notation, the first two
digits represent the red (RR) color value, the next two digits represent the green (GG) color
value, and the last two digits represent the blue (BB) color value.

The black color notation in hexadecimal is #000000, and the white color notation in
hexadecimal is #FFFFFF. Some of the codes in hexadecimal notation are #FF0000, #00FF00,
#0000FF, #FFFF00, and many more.

Syntax
color:#(0-F)(0-F)(0-F)(0-F)(0-F)(0-F);

Short Hex codes


It is a short form of hexadecimal notation in which every digit is recreated to arrive at an
equivalent hexadecimal value.
For example, #7B6 becomes #77BB66 in hexadecimal.
The black color notation in short hex is #000, and the white color notation in short hex is #FFF.
Some of the codes in short hex are #F00, #0F0, #0FF, #FF0, and many more.

HSL
It is a short form of Hue, Saturation, and Lightness. Let's understand them individually.
Hue: It can be defined as the degree on the color wheel from 0 to 360. 0 represents red, 120
represents green, 240 represents blue.
Saturation: It takes value in percentage in which 100% represents fully saturated, i.e., no
shades of gray, 50% represent 50% gray, but the color is still visible, and 0% represents fully
unsaturated, i.e., completely gray, and the color is invisible.
Lightness: The lightness of the color can be defined as the light that we want to provide the
color in which 0% represents black (there is no light), 50% represents neither dark nor light,
and 100% represents white (full lightness).

Syntax
color:hsl(H, S, L);

HSLA
It is entirely similar to HSL property, except that it contains A (alpha) that specifies the
element's transparency. The value of alpha is in the range 0.0 to 1.0, in which 0.0 indicates
fully transparent, and 1.0 indicates not transparent.

Syntax
color:hsla(H, S, L, A);

Built-in Color
As its name implies, built-in color means the collection of previously defined colors that are
used by using a name such as red, blue, green, etc.

Syntax
color: color-name;
Example Program

<html>
<head>
<title>CSS hsl color property</title>
<style>
h1{
text-align:center;
}
#rgb{
color:rgb(255,0,0);
}
#rgba{
color:rgba(255,0,0,0.5);
}
#hex{
color:#EE82EE;
}
#short{
color: #E8E;
}
#hsl{
color:hsl(0,50%,50%);
}
#hsla{
color:hsla(0,50%,50%,0.5);
}
#built{
color:green;
}
</style>
</head>
<body>
<h1 id="rgb">
Hello World. This is RGB format.
</h1>
<h1 id="rgba">
Hello World. This is RGBA format.
</h1>
<h1 id="hex">
Hello World. This is Hexadecimal format.
</h1>
<h1 id="short">
Hello World. This is Short-hexadecimal format.
</h1>
<h1 id="hsl">
Hello World. This is HSL format.
</h1>
<h1 id="hsla">
Hello World. This is HSLA format.
</h1>
<h1 id="built">
Hello World. This is Built-in color format.
</h1>
</body>
</html>
Output:
Hello World. This is RGB format.
Hello World. This is RGBA format.
Hello World. This is Hexadecimal format.
Hello World. This is Short-hexadecimal format.
Hello World. This is HSL format.
Hello World. This is HSLA format.
Hello World. This is Built-in color format.

Text Color: It is used to set the color of the text.

Syntax:
h1 {
color:color_name;
}

Example Program:
<html>
<head>
<title>CSS text color property</title>
<style>
h1 {
color:#009900;
text-align:center;
}
</style>
</head>
<body>
<h1>
B.M.S College of Engineering
</h1>
</body>
</html>

Output:

Background Color: It is used to set the background color of an HTML element.

Syntax:
h1 {
background-color:color_name;
}

Example Program:

<!DOCTYPE html>
<html>
<head>
<title>background-color property</title>
<style>
body {
text-align:center;
background-color:green;
}
h1 {
color:white;
background-color:blue;
}
h2 {
color:white;
background-color:black;
}
</style>
</head>
<body>
<h1>B.M.S College of Engineering</h1>
<h2>background-color: color_name;</h2>
</body>
</html>

Output:

Border Color: It is used to set the border color of an element. Border-style is used to set
the border type.

Syntax:
h1 {
border-style:solid/dashed/dotted
border-color:color_name;
}

Example Program:
<!DOCTYPE html>
<html>
<head>
<title>CSS border-color property</title>
<style>
h1 {
color: #009900;
}

p.one {
border-style: solid;
border-color: blue;
}

p.two {
border-style: solid;
border-color: blue red yellow green;
}

p.three {
border-style: solid;
color: green;
}
</style>
</head>

<body>
<h1 align="center">B.M.S College of Engineering</h1>
<p class="one">A solid blue border</p>

<p class="two">A solid multicolor border</p>

<p class="three">A solid inherited color border</p>

</body>
</html>

Output:

Background Image Syntax

The first step is to make sure you create an assets directory (folder) to hold the images you
want to use in your project.

For example, we can create an images folder in the project we are working on and add an
image called sunset.png that we want to use.
The background-image CSS property allows you to then place the image behind any HTML
element you wish.

This could either be the whole page (by using the body selector in CSS which targets
the <body> element in our HTML), or just a standalone specific part of the page such as
a section element like in the example below.

To add a background-image to a section tag in your .css file, write the following code:
section {
background-image: url("images/sunset.png");
}

• section specifies the tag you want to add the image to.
• url() is used to tell CSS where our image is located.
• Inside the parentheses, "images/sunset.png" is the path to the image. This lets the browser
know what URL to pull.
• The path in this example is called a relative path which means it is a local file, relative to
our project and to our current working directory and is not a web address. To add images
we can also use an absolute path, which is a full web address and starts with a domain
URL (http://www.).
• Using quotes is a good habit but we can omit them, so background-image:
url(images/sunset.png) works the same.
• Don't forget the semicolon!

How to Stop Background Repeat


When you apply a background image to an element, by default it will repeat itself.
If the image is smaller than the tag of which it's the background, it will repeat in order to fill in
the tag.

How do we stop this from happening?


The background-repeat property takes in 4 values and we are able to change the direction in
which the image repeats, or stop the image from repeating itself all together.

section {
background-repeat: repeat;
}

This is the default value if we don't give the background-repeat property a value. In this case
the image is repeated both horizontally and vertically so in both x-direction and y-
direction respectively until it fills the space.
section {
background-repeat: no-repeat;
}

The no-repeat value stops the image from repeating itself from all directions. The image is
only shown once.

section {
background-repeat: repeat-x;
}
This value repeats the image only horizontally on the page. The image is repeated across the
page, in the x-direction. The x-direction in math is from the left to the right.

section {
background-repeat: repeat-y;
}
This value repeats the image only vertically on the page. The image is repeated down the page,
in the y-direction. The y-direction in math is from top to bottom.

How to Set Background Position


After adding a background image and stopping it from repeating, we are able to further control
how it looks within the background of the tag by improving its position.
We'll use the background-position property to do this.
The selector takes in two values. The first one is for the horizontal position, or x-direction (how
far across the tag). The second one is for the vertical position, or y-direction (how far down the
tag).
The values can be units, like a pair of pixels:
section {
background-position: 20px 30px;
}
This will move the image 20px across and 30px down the containing tag.

Instead of pixels we can use a set of keywords like right, left, top, down, or center to place
the image at the right, left, top, down, or center of the tag.

section {
background-position: right center;
}
This places the image at the right hand side of the center of the tag.

If we wanted to center it both horizontally and vertically, we would do the following:


section {
background-position: center center;
}
To position an image with finer detail, it is worth mentioning that we can use percentages.
section {
background-position: 20% 40%;
}
This positions the image 20% across the tag and 40% down the tag.
So far we have seen values used in combination, but we can also just specify one value
like background-position: 20px; or background-position: center; or background-
position: 20%;, which applies it to both directions.

If only one keyword is given, the other is assumed to be center. So top is equivalent to top
center(center top) and left is same as center left(left center).

How to Resize a Background Image


To control the size of the background image we can use the background-size property.
Again, like the previous properties mentioned, it takes in two values. One for the horizontal (x)
size and one for the vertical (y) size.

We can use pixels, like so:


section {
background-size: 20px 40px;
/* sizes the image 20px across and 40px down the page */
}
If we do not know the exact width of the container we are storing the image in, there is a set
of specific values we can give the property.
• background-size: cover; resizes the background image so it covers up the whole tag's
background space no matter the width of the tag. If the image is too big and has a larger ratio
to the tag it is in, this means the image will get stretched and therefore cropped at its edges.

• background-size: contain; contains the image, as the name suggests. It will make sure the
whole image is shown in the background without cropping out any of it. If the image is much
smaller than the tag there will be space left empty which will make it repeat to fill it up, so
we can use the background-repeat: no-repeat; rule we mentioned earlier.
The rule background-size:cover; in this case will crop of parts of the image

When we change it to background-size:contain; we see that the image shrinks to fit the
section tag.

How to Use the Background Attachment Property


With the background-attachment property we can control where the background image is
attached, meaning if the image is fixed or not to the browser.
The default value is background-attachment: scroll;, where the background image stays
with its tag and follows the natural flow of the page by scrolling up and down as we scroll up
and down.
The second value the property can have is background-attachement: fixed;.
This makes the background image stay in the same postion, fixed to the page and fixed on the
browser's viewport. This creates a parallax effect which you can see an example of here:
Background Gradients
A different use case for the background-image property is for telling the browser to create a
gradient.
The background-image in this case does not have a URL, but a linear-gradient instead.
The simplest way to do this is to specify the angle. This controls the direction of the gradient
and how to colors will blend. Lastly add two colors that you want blended together in a gradient
for the tag's background.

A gradient that goes from top to bottom and from black to white is:
section {
background-image: linear-gradient(black,white);
}

The most common degrees used for gradients are:


• 0deg from top to bottom
• 90deg from left to right
• 180deg from bottom to top
• 270deg from right to left
The above degrees each correspond with to top, to right, to bottom and to left,
respectively.

section{
background-image: linear-gradient(to left,pink,orange);
}

Instead of keyword colors we can use hex colors to be more particular and have a wider range
of options:
section{
background-image: linear-gradient(to left,#42275a, #734b6d)
}

We can also include more than two colors in a gradient, creating different affects and color
schemes.

Property Values
Value Description

url('URL') The URL to the image. To specify more than one


image, separate the URLs with a comma

none No background image will be displayed. This is


default

conic-gradient() Sets a conic gradient as the background image.


Define at least two colors

linear-gradient() Sets a linear gradient as the background image.


Define at least two colors (top to bottom)
radial-gradient() Sets a radial gradient as the background image.
Define at least two colors (center to edges)

repeating-conic-gradient() Repeats a conic gradient

repeating-linear-gradient() Repeats a linear gradient

repeating-radial-gradient() Repeats a radial gradient

initial Sets this property to its default value. Read


about initial

inherit Inherits this property from its parent element. Read


about inherit

Example Program:

<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("paper.gif");
}
</style>
</head>
<body>

<h1>The background-image Property</h1>

<p>
This demo shows some different techiques on how to set a background image of a HTML
element.
</p>

</body>
</html>

Note:
For more example programs on background-image, please visit
https://www.w3schools.com/cssref/pr_background-image.php
CSS Position Properties

The position property specifies the type of positioning method used for an element.

There are three different position values:

• static
• relative
• absolute

Elements are then positioned using the top, bottom, left, and right properties. However, these
properties will not work unless the position property is set first. They also work differently
depending on the position value.

position: static
• HTML elements are positioned static by default.
• Static positioned elements are not affected by the top, bottom, left, and right properties.
• An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page.

Example program:

<!DOCTYPE html>
<html>
<head>
<style>
div.static {
position: static;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: static;</h2>

<p>An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page:</p>

<div class="static">
This div element has position: static;
</div>

</body>
</html>

Output:
position: relative;

An element with position: relative; changes the position of the element relative to the parent
element and relative to itself and where it would usually be in the regular document flow of the
page. This means that it's relative to its original position within the parent element. It moves
the tag based on where it currently is, relative to its usual place and relative to its surrounding
tags without affecting their layout. Setting the top, right, bottom, and left properties of a
relatively-positioned element will cause it to be adjusted away from its normal position.

Example Program:

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: relative;</h2>

<p>An element with position: relative; is positioned relative to its normal position:</p>

<div class="relative">
This div element has position: relative;
</div>

</body>
</html>

Output:
position: absolute;

An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the document
body(<htmlM element), and moves along with page scrolling.

Note: Absolute positioned elements are removed from the normal flow, and can overlap
elements.

Example Program:

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed):</p>

<div class="relative">This div element has position: relative;


<div class="absolute">This div element has position: absolute;</div>
</div>
</body>
</html>

Output:

You might also like