0% found this document useful (0 votes)
48 views

2 - CSS Notes

CSS is a standard style sheet language used for describing the presentation of web pages. CSS separates presentation from content, allowing consistent styles across multiple pages. CSS rules can be applied via inline styles, embedded stylesheets, or external stylesheets. External stylesheets are preferred for maintenance and reuse.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

2 - CSS Notes

CSS is a standard style sheet language used for describing the presentation of web pages. CSS separates presentation from content, allowing consistent styles across multiple pages. CSS rules can be applied via inline styles, embedded stylesheets, or external stylesheets. External stylesheets are preferred for maintenance and reuse.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 160

CSS GETTING STARTED NOTES

CSS stands for Cascading Style Sheets. CSS is a standard style sheet language used for
describing the presentation (i.e. the layout and formatting) of the web pages. Prior to CSS,
nearly all of the presentational attributes of HTML documents were contained within the
HTML markup (specifically inside the HTML tags); all font colors, background styles, element
alignments, borders and sizes had to be explicitly described within the HTML. As a result,
development of the large websites became a long and expensive process, since the style
information were repeatedly added to every single page of the website.

To solve this problem CSS was introduced in 1996 by the World Wide Web Consortium
(W3C), which also maintains its standard. CSS was designed to enable the separation of
presentation and content. Now web designers can move the formatting information of the
web pages to a separate style sheet which results in considerably simpler HTML markup, and
better maintainability. CSS3 is the latest version of the CSS specification. CSS3 adds several
new styling features and improvements to enhance the web presentation capabilities.

What You Can Do with CSS


There are lot more things you can do with CSS.

 You can easily apply same style rules on multiple elements.


 You can control the presentation of multiple pages of a website with a single style
sheet.
 You can present the same page differently on different devices.
 You can style dynamic states of elements such as hover, focus, etc. that isn't possible
otherwise.
 You can change the position of an element on a web page without changing the
markup.
 You can alter the display of existing HTML elements.
 You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
 You can create animations and transitions effects without using any JavaScript.
 You can create print friendly version of your web pages.

The list does not end here, there are many other interesting things that you can do with CSS.
You will learn about all of them in detail in upcoming chapters.

Advantages of Using CSS


The biggest advantage of CSS is that it allows the separation of style and layout from the
content of the document. Here are some more advantages, why one should start using CSS?
 CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an
element. You can write CSS once; and then the same code can be applied to the groups of
HTML elements, and can also be reused in multiple HTML pages.
 Easy Maintenance — CSS provides an easy means to update the formatting of the
documents, and to maintain the consistency across multiple documents. Because the
content of the entire set of web pages can be easily controlled using one or more style
sheets.
 Pages Load Faster — CSS enables multiple pages to share the formatting information,
which reduces complexity and repetition in the structural contents of the documents. It
significantly reduces the file transfer size, which results in a faster page loading.
 Superior Styles to HTML — CSS has much wider presentation capabilities than HTML and
provide much better control over the layout of your web pages. So you can give far better
look to your web pages in comparison to the HTML presentational elements and
attributes.
 Multiple Device Compatibility — CSS also allows web pages to be optimized for more
than one type of device or media. Using CSS the same HTML document can be presented
in different viewing styles for different rendering devices such as desktop, cell phones, etc.

Getting Started with CSS


In this tutorial you'll learn how easy it is to add style and formatting information to the web
pages using CSS. But, before we begin, make sure that you have some working knowledge of
HTML. If you're just starting out in the world of web development, start learning from here »

Without further ado, let's get started with the Cascading Style Sheets (CSS).

Including CSS in HTML Documents


CSS can either be attached as a separate document or embedded in the HTML document
itself. There are three methods of including CSS in an HTML document:

 Inline styles — Using the style attribute in the HTML start tag.
 Embedded styles — Using the <style> element in the head section of a document.
 External style sheets — Using the <link> element, pointing to an external CSS file.

In this tutorial we will cover all these three methods for inserting CSS one by one.

Note: The inline styles have the highest priority, and the external style sheets have the lowest.
It means if you specify styles for an element in both embedded and external style sheets, the
conflicting style rules in the embedded style sheet would override the external style sheet.
Inline Styles
Inline styles are used to apply the unique style rules to an element by putting the CSS rules
directly into the start tag. It can be attached to an element using the style attribute.
The style attribute includes a series of CSS property and value pairs. Each "property:
value" pair is separated by a semicolon (;), just as you would write into an embedded or
external style sheets. But it needs to be all in one line i.e. no line break after the semicolon, as
shown here:

Example
Try this code »
<h1 style="color:red; font-size:30px;">This is a heading</h1>
<p style="color:green; font-size:22px;">This is a paragraph.</p>
<div style="color:blue; font-size:14px;">This is some text content.</div>
Using the inline styles are generally considered as a bad practice. As style rules are embedded
directly inside the HTML tag, it causes the presentation to become mixed with the content of
the document; which makes the code hard to maintain and negates the purpose of using CSS.

Note: It's become impossible to style pseudo-elements and pseudo-classes with inline styles.
You should, therefore, avoid the use of style attributes in your code. Using external style
sheets is the preferred way to add styles to the HTML documents.

Embedded Style Sheets


Embedded or internal style sheets only affect the document they are embedded in. Embedded
style sheets are defined in the <head> section of an HTML document using the <style> element.
You can define any number of <style> elements in an HTML document but they must appear
between the <head> and </head> tags. Let's take a look at an example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>My HTML Document</title>
<style>
body { background-color: YellowGreen; }
p { color: #fff; }
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
Tip: The type attribute of the <style> and <link> tag (i.e. type="text/css") defines the language
of the style sheet. This attribute is purely informative. You can omit this since CSS is the
standard and default style sheet language in HTML5.

External Style Sheets


An external style sheet is ideal when the style is applied to many pages of the website. An
external style sheet holds all the style rules in a separate document that you can link from any
HTML file on your site. External style sheets are the most flexible because with an external
style sheet, you can change the look of an entire website by changing just one file.

You can attach external style sheets in two ways — linking and importing.

Linking External Style Sheets


Before linking, we need to create a style sheet first. Let's open your favorite code editor and
create a new file. Now type the following CSS code inside this file and save it as "style.css".

Example
Try this code »
body {
background: lightyellow;
font: 18px Arial, sans-serif;
}
h1 {
color: orange;
}
An external style sheet can be linked to an HTML document using the <link> tag.
The <link> tag goes inside the <head> section, as you can see in the following example:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<title>My HTML Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
Tip: Among all the three methods, using external style sheet is the best method for defining
and applying styles to the HTML documents. As you can clearly see with external style sheets,
the affected HTML file require minimal changes in the markup.

Importing External Style Sheets


The @import rule is another way of loading an external style sheet. The @import statement
instructs the browser to load an external style sheet and use its styles. You can use it in two
ways. The simplest is within the header of your document. Note that, other CSS rules may still
be included in the <style> element. Here's an example:

Example
Try this code »
<style>
@import url("css/style.css");
p {
color: blue;
font-size: 16px;
}
</style>
Similarly, you can use the @import rule to import a style sheet within another style sheet.

Example
Try this code »
@import url("css/layout.css");
@import url("css/color.css");
body {
color: blue;
font-size: 14px;
}
Note: All @import rules must occur at the start of the style sheet. Any style rule defined in the
style sheet itself override the conflicting rules in the imported style sheets. However,
importing a style sheet within another style sheet is not recommended due to performance
issue.

CSS Syntax. Understanding CSS Syntax


A CSS stylesheet consists of a set of rules that are interpreted by the web browser and then
applied to the corresponding elements such as paragraphs, headings, etc. in the document.

A CSS rule have two main parts, a selector and one or more declarations:
The selector specifies which element or elements in the HTML page the CSS rule applies to.

Whereas, the declarations within the block determines how the elements are formatted on a
webpage. Each declaration consists of a property and a value separated by a colon (:) and
ending with a semicolon (;), and the declaration groups are surrounded by curly braces {}.

The property is the style attribute you want to change; they could be font, color, background,
etc. Each property has a value, for example color property can have value
either blue or #0000FF etc.

h1 {color:blue; text-align:center;}
To make the CSS more readable, you can put one declaration on each line, like this:

Example
Try this code »
h1 {
color: blue;
text-align: center;
}
In the example above h1 is a selector, color and text-align are the CSS properties, and the
given blue and center are the corresponding values of these properties.

Note: A CSS declaration always ends with a semicolon ";", and the declaration groups are
always surrounded by the curly brackets "{}".

Writing Comments in CSS


Comments are usually added with the purpose of making the source code easier to know. It
may help other developer (or you in the future when you edit the source code) to understand
what you were trying to do with the CSS. Comments are significant to programmers but
ignored by browsers. A CSS comment begins with /*, and ends with */, as shown in the
example below:

Example
Try this code »
/* This is a CSS comment */
h1 {
color: blue;
text-align: center;
}
/* This is a multi-line CSS comment
that spans across more than one line */
p {
font-size: 18px;
text-transform: uppercase;
}
You can also comment out part of your CSS code for debugging purpose, as shown here:

Example
Try this code »
h1 {
color: blue;
text-align: center;
}
/*
p {
font-size: 18px;
text-transform: uppercase;
}
*/

Case Sensitivity in CSS


CSS property names and many values are not case-sensitive. Whereas, CSS selectors are
usually case-sensitive, for instance, the class selector .maincontent is not the same
as .mainContent. Therefore, to be on safer side, you should assume that all components of CSS
rules are case-sensitive.

CSS Selectors. What is Selector?


A CSS selector is a pattern to match the elements on a web page. The style rules associated
with that selector will be applied to the elements that match the selector pattern. Selectors are
one of the most important aspects of CSS as they allow you to target specific elements on
your web page in various ways so that they can be styled. Several types of selectors are
available in CSS, let's take a closer look at them:

Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page.
The universal selector may be omitted if other conditions exist on the element. This selector is
often used to remove the default margins and paddings from the elements for quick testing
purpose. Let's try out the following example to understand how it basically works:

Example
Try this code »
* {
margin: 0;
padding: 0;
}
The style rules inside the * selector will be applied to every element in a document.

Note: It is recommended not to use the universal selector (*) too often in a production
environment, since this selector matches every element on a web page that puts too much of
unnecessary pressure on the browsers. Use element type or class selector instead.

Element Type Selectors


An element type selector matches all instance of the element in the document with the
corresponding element type name. Let's try out an example to see how it actually works:

Example
Try this code »
p {
color: blue;
}
The style rules inside the p selector will be applied on every <p> element (or paragraph) in the
document and color it blue, regardless of their position in the document tree.

Id Selectors
The id selector is used to define style rules for a single or unique element. The id selector is
defined with a hash sign (#) immediately followed by the id value.

Example
Try this code »
#error {
color: red;
}
This style rule renders the text of an element in red, whose id attribute is set to error.
Note: The value of an id attribute must be unique within a given document — meaning no
two elements in your HTML document can share the same id value.

Class Selectors
The class selectors can be used to select any HTML element that has a class attribute. All the
elements having that class will be formatted according to the defined rule. The class selector
is defined with a period sign (.) immediately followed by the class value.

Example
Try this code »
.blue {
color: blue;
}
The above style rules renders the text in blue of every element in the document that
has class attribute set to blue. You can make it a bit more particular. For example:

Example
Try this code »
p.blue {
color: blue;
}
The style rule inside the selector p.blue renders the text in blue of only those <p> elements that
has class attribute set to blue, and has no effect on other paragraphs.

Descendant Selectors
You can use these selectors when you need to select an element that is the descendant of
another element, for example, if you want to target only those anchors that are contained
within an unordered list, rather than targeting all anchor elements. Let's see how it works:

Example
Try this code »
ul.menu li a {
text-decoration: none;
}
h1 em {
color: green;
}
The style rules inside the selector ul.menu li a applied to only those <a> elements that
contained inside an <ul> element having the class .menu, and has no effect on other links inside
the document.
Similarly, the style rules inside the h1 em selector will be applied to only those <em> elements
that contained inside the <h1> element and has not effect on other <em> elements.

Child Selectors
A child selector is used to select only those elements that are the direct children of some
element. A child selector is made up of two or more selectors separated by a greater than
symbol (>). You can use this selector, for instance, to select the first level of list elements inside
a nested list that has more than one level. Let's check out an example to understand how it
works:

Example
Try this code »
ul > li {
list-style: square;
}
ul > li ol {
list-style: none;
}
The style rule inside the selector ul > li applied to only those <li> elements that are direct
children of the <ul> elements, and has no effect on other list elements.

Adjacent Sibling Selectors


The adjacent sibling selectors can be used to select sibling elements (i.e. elements at the same
level). This selector has the syntax like: E1 + E2, where E2 is the target of the selector. The
selector h1 + p in the following example will select the <p> elements only if both
the <h1> and <p> elements share the same parent in the document tree and <h1> is immediately
precedes the <p> element. That means only those paragraphs that come immediately after
each <h1> heading will have the associated style rules. Let's see how this selector actually
works:

Example
Try this code »
h1 + p {
color: blue;
font-size: 18px;
}
ul.task + p {
color: #f0f;
text-indent: 30px;
}
General Sibling Selectors
The general sibling selector is similar to the adjacent sibling selector (E1 + E2), but it is less
strict. A general sibling selector is made up of two simple selectors separated by the tilde (∼)
character. It can be written like: E1 ∼ E2, where E2 is the target of the selector. The selector h1
∼ p in the example below will select all the <p> elements that preceded by the <h1> element,
where all the elements share the same parent in the document tree.

Example
Try this code »

h1 ∼ p {
color: blue;
font-size: 18px;
}
ul.task ∼ p {
color: #f0f;
text-indent: 30px;
}
There are more sophisticated selectors like attribute selectors, pseudo-classes, pseudo-
elements. We will discuss about these selectors in detail in the upcoming chapters.

Grouping Selectors
Often several selectors in a style sheet share the same style rules declarations. You can group
them into a comma-separated list to minimize the code in your style sheet. It also prevents
you from repeating the same style rules over and over again. Let's take a look:

Example
Try this code »
h1 {
font-size: 36px;
font-weight: normal;
}
h2 {
font-size: 28px;
font-weight: normal;
}
h3 {
font-size: 22px;
font-weight: normal;
}
As you can see in the above example, the same style rule font-weight: normal; is shared by the
selectors h1, h2 and h3, so it can be grouped in a comma-separated list, like this:
Example
Try this code »
h1, h2, h3 {
font-weight: normal;
}
h1 {
font-size: 36px;
}
h2 {
font-size: 28px;
}
h3 {
font-size: 22px;
}

CSS Color. Setting Color Property


The color property defines the text color (foreground color in general) of an element. For
instance, the color property specified in the body selector defines the default text color for the
whole page. Let's try out the following example to see how it works:

Example
Try this code »
body {
color: #ff5722;
}
Note: The color property normally inherits the color value from their parent element, except
the case of anchor elements. For example, if you specify color for the body element it will
automatically be passed down to the headings, paragraphs, etc.

Defining Color Values


Colors in CSS most often specified in the following formats:

 a color keyword - like "red", "green", "blue", "transparent", etc.


 a HEX value - like "#ff0000", "#00ff00", etc.
 an RGB value - like "rgb(255, 0, 0)"
CSS3 has introduced several other color formats such as HSL, HSLA and RGBA that also
support alpha transparency. We'll learn about them in greater detail in CSS3 color chapter.

For now, let's stick to the basic methods of defining the color values:

Color Keywords
CSS defines the few color keywords which lets you specify color values in an easy way. These
basic color keywords are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive,
purple, red, silver, teal, white, and yellow. The color names are case-insensitive.

Example
Try this code »
h1 {
color: red;
}
p {
color: purple;
}
Modern web browsers however practically support many more color names than what are
defined in the CSS standard, but to be on the safer side you should use hex color values
instead. See the reference on CSS color names, for a complete list of possible color names.

CSS Color Names


The color names are case-insensitive.

Basic color keywords


The following table lists the basic color keywords defined in CSS3 specification.

Color Name Hex Value RGB Value

aqua #00FFFF rgb(0, 255, 255)

black #000000 rgb(0, 0, 0)

blue #0000FF rgb(0, 0, 255)

fuchsia #FF00FF rgb(255, 0, 255)


gray #808080 rgb(128, 128, 128)

green #008000 rgb(0, 128, 0)

lime #00FF00 rgb(0, 255, 0)

maroon #800000 rgb(128, 0, 0)

navy #000080 rgb(0, 0, 128)

olive #808000 rgb(128, 128, 0)

purple #800080 rgb(128, 0, 128)

red #FF0000 rgb(255, 0, 0)

silver #C0C0C0 rgb(192, 192, 192)

teal #008080 rgb(0, 128, 128)

white #FFFFFF rgb(255, 255, 255)

yellow #FFFF00 rgb(255, 255, 0)

Extended color keywords


The following table lists the extended color keywords defined in CSS3 specification.

Color Name Hex Value RGB Value

aliceblue #F0F8FF rgb(240, 248, 255)

antiquewhite #FAEBD7 rgb(250, 235, 215)

aqua #00FFFF rgb(0, 255, 255)

aquamarine #7FFFD4 rgb(127, 255, 212)

azure #F0FFFF rgb(1240, 255, 255)

beige #F5F5DC rgb(245, 245, 220)

bisque #FFE4C4 rgb(255, 228, 196)


black #000000 rgb(0, 0, 0)

blanchedalmond #FFEBCD rgb(255, 235, 205)

blue #0000FF rgb(0, 0, 255)

blueviolet #8A2BE2 rgb(138, 43, 226)

brown #A52A2A rgb(165, 42, 42)

burlywood #DEB887 rgb(222, 184, 135)

cadetblue #5F9EA0 rgb(95, 158, 160)

chartreuse #7FFF00 rgb(95, 158, 160)

chocolate #D2691E rgb(210, 105, 30)

coral #FF7F50 rgb(255, 127, 80)

cornflowerblue #6495ED rgb(100, 149, 237)

cornsilk #FFF8DC rgb(255, 248, 220)

crimson #DC143C rgb(220, 20, 60)

cyan #00FFFF rgb(0, 255, 255)

darkblue #00008B rgb(0, 0, 139)

darkcyan #008B8B rgb(0, 139, 139)

darkgoldenrod #B8860B rgb(184, 134, 11)

darkgray #A9A9A9 rgb(169, 169, 169)

darkgreen #006400 rgb(0, 100, 0)

darkkhaki #BDB76B rgb(189, 183, 107)

darkmagenta #8B008B rgb(139, 0, 139)

darkolivegreen #556B2F rgb(85, 107, 47)

darkorange #FF8C00 rgb(255, 140, 0)


darkorchid #9932CC rgb(153, 50, 204)

darkred #8B0000 rgb(139, 0, 0)

darksalmon #E9967A rgb(233, 150, 122)

darkseagreen #8FBC8F rgb(143, 188, 143)

darkslateblue #483D8B rgb(72, 61, 139)

darkslategray #2F4F4F rgb(47, 79, 79)

darkturquoise #00CED1 rgb(0, 206, 209)

darkviolet #9400D3 rgb(148, 0, 211)

deeppink #FF1493 rgb(255, 20, 147)

deepskyblue #00BFFF rgb(0, 191, 255)

dimgray #696969 rgb(0, 191, 255)

dodgerblue #1E90FF rgb(30, 144, 255)

firebrick #B22222 rgb(178, 34, 34)

floralwhite #FFFAF0 rgb(255, 250, 240)

forestgreen #228B22 rgb(34, 139, 34)

fuchsia #FF00FF rgb(255, 0, 255)

gainsboro #DCDCDC rgb(220, 220, 220)

ghostwhite #F8F8FF rgb(248, 248, 255)

gold #FFD700 rgb(255, 215, 0)

goldenrod #DAA520 rgb(218, 165, 32)

gray #7F7F7F rgb(127, 127, 127)

green #008000 rgb(0, 128, 0)

greenyellow #ADFF2F rgb(173, 255, 47)


honeydew #F0FFF0 rgb(240, 255, 240)

hotpink #FF69B4 rgb(255, 105, 180)

indianred #CD5C5C rgb(205, 92, 92)

indigo #4B0082 rgb(75, 0, 130)

ivory #FFFFF0 rgb(255, 255, 240)

khaki #F0E68C rgb(240, 230, 140)

lavender #E6E6FA rgb(230, 230, 250)

lavenderblush #FFF0F5 rgb(255, 240, 245)

lawngreen #7CFC00 rgb(124, 252, 0)

lemonchiffon #FFFACD rgb(255, 250, 205)

lightblue #ADD8E6 rgb(173, 216, 230)

lightcoral #F08080 rgb(240, 128, 128)

lightcyan #E0FFFF rgb(224, 255, 255)

lightgoldenrodyellow #FAFAD2 rgb(250, 250, 210)

lightgreen #90EE90 rgb(144, 238, 144)

lightgrey #D3D3D3 rgb(211, 211, 211)

lightpink #FFB6C1 rgb(255, 182, 193)

lightsalmon #FFA07A rgb(255, 160, 122)

lightseagreen #20B2AA rgb(32, 178, 170)

lightskyblue #87CEFA rgb(135, 206, 250)

lightslategray #778899 rgb(119, 136, 153)

lightsteelblue #B0C4DE rgb(176, 196, 222)

lightyellow #FFFFE0 rgb(255, 255, 224)


lime #00FF00 rgb(0, 255, 0)

limegreen #32CD32 rgb(50, 205, 50)

linen #FAF0E6 rgb(250, 240, 230)

magenta #FF00FF rgb(255, 0, 255)

maroon #800000 rgb(128, 0, 0)

mediumaquamarine #66CDAA rgb(102, 205, 170)

mediumblue #0000CD rgb(0, 0, 205)

mediumorchid #BA55D3 rgb(186, 85, 211)

mediumpurple #9370DB rgb(147, 112, 219)

mediumseagreen #3CB371 rgb(60, 179, 113)

mediumslateblue #7B68EE rgb(123, 104, 238)

mediumspringgreen #00FA9A rgb(0, 250, 154)

mediumturquoise #48D1CC rgb(72, 209, 204)

mediumvioletred #C71585 rgb(199, 21, 133)

midnightblue #191970 rgb(25, 25, 112)

mintcream #F5FFFA rgb(245, 255, 250)

mistyrose #FFE4E1 rgb(255, 228, 225)

moccasin #FFE4B5 rgb(255, 228, 181)

navajowhite #FFDEAD rgb(255, 222, 173)

navy #000080 rgb(0, 0, 128)

navyblue #9FAFDF rgb(159, 175, 223)

oldlace #FDF5E6 rgb(253, 245, 230)

olive #808000 rgb(128, 128, 0)


olivedrab #6B8E23 rgb(107, 142, 35)

orange #FFA500 rgb(255, 165, 0)

orangered #FF4500 rgb(255, 69, 0)

orchid #DA70D6 rgb(218, 112, 214)

palegoldenrod #EEE8AA rgb(238, 232, 170)

palegreen #98FB98 rgb(152, 251, 152)

paleturquoise #AFEEEE rgb(175, 238, 238)

palevioletred #DB7093 rgb(219, 112, 147)

papayawhip #FFEFD5 rgb(255, 239, 213)

peachpuff #FFDAB9 rgb(255, 218, 185)

peru #CD853F rgb(205, 133, 63)

pink #FFC0CB rgb(255, 192, 203)

plum #DDA0DD rgb(221, 160, 221)

powderblue #B0E0E6 rgb(176, 224, 230)

purple #800080 rgb(128, 0, 128)

red #FF0000 rgb(255, 0, 0)

rosybrown #BC8F8F rgb(188, 143, 143)

royalblue #4169E1 rgb(65, 105, 225)

saddlebrown #8B4513 rgb(139, 69, 19)

salmon #FA8072 rgb(250, 128, 114)

sandybrown #FA8072 rgb(244, 164, 96)

seagreen #2E8B57 rgb(46, 139, 87)

seashell #FFF5EE rgb(255, 245, 238)


sienna #A0522D rgb(160, 82, 45)

silver #C0C0C0 rgb(192, 192, 192)

skyblue #87CEEB rgb(135, 206, 235)

slateblue #6A5ACD rgb(106, 90, 205)

slategray #708090 rgb(112, 128, 144)

snow #FFFAFA rgb(255, 250, 250)

springgreen #00FF7F rgb(0, 255, 127)

steelblue #4682B4 rgb(70, 130, 180)

tan #D2B48C rgb(210, 180, 140)

teal #008080 rgb(0, 128, 128)

thistle #D8BFD8 rgb(216, 191, 216)

tomato #FF6347 rgb(255, 99, 71)

turquoise #40E0D0 rgb(64, 224, 208)

violet #EE82EE rgb(238, 130, 238)

wheat #F5DEB3 rgb(245, 222, 179)

white #FFFFFF rgb(255, 255, 255)

whitesmoke #F5F5F5 rgb(245, 245, 245)

yellow #FFFF00 rgb(255, 255, 0)

yellowgreen #9ACD32 rgb(139, 205, 50)

HEX Color Values


Hex (short for Hexadecimal) is by far the most commonly used method of defining color on
the web. Hex represent colors using a six-digit code, preceded by a hash character,
like #rrggbb, in which rr, gg, and bb represents the red, green and blue component of the color
respectively. The value of each component can vary from 00 (no color) and FF (full color) in
hexadecimal notation, or 0 and 255 in decimal equivalent notation. Thus #ffffff represents
white color and #000000 represents black color. Let's take a look the following example:

Example
Try this code »
h1 {
color: #ffa500;
}
p {
color: #00ff00;
}
Note: Hexadecimal or Hex refers to a numbering scheme that uses 16 characters as its base. It
uses the numbers 0 through 9 and the letters A, B, C, D, E and F which corresponds to the
decimal numbers 10, 11, 12, 13, 14 and 15 respectively.

Tip: If hexadecimal code of a color has value pairs, it can also be written in shorthand notation
to avoid extra typing, for example, the hex color value #ffffff can be also be written as #fff,
#000000 as #000, #00ff00 as #0f0, #ffcc00 as #fc0, and so on.

RGB Color Values


Colors can be defined in the RGB model (Red, Green, and Blue) using the rgb() functional
notation. The rgb() function accepts three comma-separated values, which specify the amount
of red, green, and blue component of the color. These values are commonly specified as
integers between 0 to 255, where 0 represent no color and 255 represent full or maximum
color. The following example specifies the same color as in the previous example but in RGB
notation.

Example
Try this code »
h1 {
color: rgb(255, 165, 0);
}
p {
color: rgb(0, 255, 0);
}
Note: You can also specify RGB values inside the rgb() function in percentage, where 100%
represents full color, and 0% (not simply 0) represents no color. For example, you can specify
the red color either as rgb(255, 0, 0) or rgb(100%, 0%, 0%).

Tip: If R, G, and B are all set to 255, i.e. rgb(255, 255, 255), the color would be white. Likewise, if
all channels are set to 0, i.e. rgb(0, 0, 0), the color would be black. Play with the RGB values in
the following demonstration to understand how it actually works.
Effect of Color Property on Borders and Outlines
The color property is not just for text content, but for anything in the foreground that takes a
color value. For instance, if border-color or outline-color value hasn't been defined explicitly for
the element, the color value will be used instead. Let's check out an example:

Example
Try this code »
p.one {
color: #0000ff;
border: 2px solid;
}
p.two {
color: #00ff00;
outline: 2px solid;
}

CSS Background. Setting Background Properties


Background plays an important role in the visual presentation of a web page.

CSS provide several properties for styling the background of an element, including coloring
the background, placing images in the background and managing their positioning, etc.

The background properties are background-color, background-image, background-repeat, background-


attachment and background-position.

In the following section we will discuss each of these properties in more detail.

Background Color
The background-color property is used to set the background color of an element.

The following example demonstrates how to set the background color of the whole page.

Example
Try this code »
body {
background-color: #f0e68c;
}
Color values in CSS are most often specified in the following formats:

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255, 0, 0)"

Please check out the tutorial on CSS color to learn more about specifying color values.

Background Image
The background-image property set an image as a background of an HTML element.

Let's check out the following example which sets the background image for the whole page.

Example
Try this code »
body {
background-image: url("images/tile.png");
}
Note: When applying the background image to an element, make sure that the image you
choose does not affect the readability of the element's text content.

Tip: By default browser repeats or tiles the background image both horizontally and vertically
to fill the entire area of an element. You can control this with background-repeat property.

Background Repeat
The background-repeat property allows you to control how a background image is repeated or
tiled in the background of an element. You can set a background image to repeat vertically (y-
axis), horizontally (x-axis), in both directions, or in neither direction. Let's try out the following
example which demonstrates how to set the gradient background for a web page by
repeating the sliced image horizontally along the x-axis.

Example
Try this code »
body {
background-image: url("images/gradient.png");
background-repeat: repeat-x;
}
Similarly, you can use the value repeat-y to repeat the background image vertically along the
y-axis, or the value no-repeat to prevent the repetition altogether.

Example
Try this code »
body {
background-image: url("images/texture.png");
background-repeat: no-repeat;
}
Let's take a look at the following illustration to understand how this property actually works.

Background Position
The background-position property is used to control the position of the background image. If no
background position has been specified, the background image is placed at the default top-
left position of the element i.e. at (0,0), let's try out the following example:

Example
Try this code »
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
}
In the following example, the background image is positioned at top-right corner.

Example
Try this code »
body {
background-image: url("images/robot.png");
background-repeat: no-repeat;
background-position: right top;
}
Note: If two values are specified for the background-position property, the first value represents
the horizontal position, and the second represents the vertical position. If only one value is
specified, the second value is assumed to be center.

Besides keywords, you can also use percentage or length values, such as px or em for this
property.
Let's take a look at the following illustration to understand how this property actually works.

Background Attachment
The background-attachment property determines whether the background image is fixed with
regard to the viewport or scrolls along with the containing block. Let's try out the following
example to understand how it basically works:

Example
Try this code »
body {
background-image: url("images/bell.png");
background-repeat: no-repeat;
background-attachment: fixed;
}

The Background Shorthand Property


As you can see in the examples above, there are many properties to consider when dealing
with the backgrounds. However, it is also possible to specify all these properties in one single
property to shorten the code or avoid extra typing. This is called a shorthand property.
The background property is a shorthand property for setting all the individual background
properties, i.e., background-color, background-image, background-repeat, background-attachment and
the background-position property at once. Let's see how this works:

Example
Try this code »
body {
background-color: #f0e68c;
background-image: url("images/smiley.png");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 250px 25px;
}
Using the shorthand notation the above example can be written as:

Example
Try this code »
body {
background: #f0e68c url("images/smiley.png") no-repeat fixed 250px
25px;
}
When using the background shorthand property the order of the property values should be.

background: color image repeat attachment position;

If the value for an individual background property is missing or not specified while using the
shorthand notation, the default value for that property will be used instead, if any.

Note: The background properties do not inherit like the color property, but the parent
element's background will be visible through by default, because of the initial or
default transparent value of the background-color CSS property.

CSS Fonts. Styling Fonts with CSS


Choosing the right font and style is very crucial for the readability of text on a page. CSS
provide several properties for styling the font of the text, including changing their face,
controlling their size and boldness, managing variant, and so on.

The font properties are: font-family, font-style, font-weight, font-size, and font-variant.

Let's discuss each of these font properties one by one in more detail.
Font Family
The font-family property is used to specify the font to be used to render the text. This property
can hold several comma-separated font names as a fallback system, so that if the first font is
not available on the user's system, browser tries to use the second one, and so on. Hence, list
the font that you want first, then any fonts that might fill in for the first if it is not available.
You should end the list with a generic font family which are five — serif, sans-
serif, monospace, cursive and fantasy. A typical font family declaration might look like this:

Example
Try this code »
body {
font-family: Arial, Helvetica, sans-serif;
}
Note: If the name of a font family contains more than one word, it must be placed inside
quotation marks, like "Times New Roman", "Courier New", "Segoe UI", etc.

The most common font families used in web design are serif and sans-serif, because they are
more suitable for reading. While monospace fonts are commonly used to display code, because
in this typeface each letter takes up the same space which looks like typewritten text.
The cursive fonts look like cursive writing or handwriting. The fantasy font represents artistic
font, but they're not used widely because of poor availability across the operating systems.

Difference Between Serif and Sans-serif Fonts


Serif fonts have small line or stroke at the extremities of characters, whereas sans-serif fonts
are straighter and do not have these small strokes. See the following illustration.

To learn about commonly used font combinations, please check out the reference on web
safe fonts.

Font Style
The font-style property is used to set the font face style for the text content of an element.
The font style can be normal, italic or oblique. The default value is normal.

Let's try out the following example to understand how it basically works:

Example
Try this code »
p.normal {
font-style: normal;
}
p.italic {
font-style: italic;
}
p.oblique {
font-style: oblique;
}
Note: At first glance both oblique and italic font styles appear the same thing, but there is a
difference. The italic style uses an italic version of the font while oblique style on the other
hand is simply a slanted or sloped version of the normal font.

Font Size
The font-size property is used to set the size of font for the text content of an element.

There are several ways to specify the font size values e.g. with keywords, percentage, pixels,
ems, etc.

Setting Font Size with Pixels


Setting the font size in pixel values (e.g. 14px, 16px, etc.) is a good choice when you need the
pixel accuracy. Pixel is an absolute unit of measurement which specifies a fixed length.

Let's try out the following example to understand how it basically works:

Example
Try this code »
h1 {
font-size: 24px;
}
p {
font-size: 14px;
}
Defining the font sizes in pixel is not considered very accessible, because the user cannot
change the font size from the browser settings. For instance, users with limited or low vision
may wish to set the font size much larger than the size specified by you.
Therefore, you should avoid using the pixels values and use the values that are relative to the
user's default font size instead if you want to create an inclusive design.

Tip: The text can also be resized in all browsers using the zoom feature. However, this feature
resizes the entire page, not just the text. The W3C recommends using the em or percentage
(%) values in order to create more robust and scalable layouts.

Setting Font Size with EM


The em unit refers to the font size of the parent element. When defining the font-
size property, 1em is equal to the size of the font that applies to the parent of the element.

So, if you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px.

However, if you haven't set the font size anywhere on the page, then it is the browser default,
which is normally 16px. Therefore, by default 1em = 16px, and 2em = 32px.

Let's take a look at the following example to understand how it basically works:

Example
Try this code »
h1 {
font-size: 2em; /* 32px/16px=2em */
}
p {
font-size: 0.875em; /* 14px/16px=0.875em */
}

Using the Combination of Percentage and EM


As you've observed in the above example the calculation of em values doesn't look
straightforward. To simplify this, a popular technique is to set the font-size for the body
element to 62.5% (that is 62.5% of the default 16px), which equates to 10px, or 0.625em.

Now you can set the font-size for any elements using em units, with an easy-to-remember
conversion, by dividing the px value by 10. This
way 10px = 1em, 12px = 1.2em, 14px = 1.4em, 16px = 1.6em, and so on. Let's take a look at the
following example:

Example
Try this code »
body {
font-size: 62.5%; /* font-size 1em = 10px */
}
p {
font-size: 1.4em; /* 1.4em = 14px */
}
p span {
font-size: 2em; /* 2em = 28px */
}

Setting Font Size with Root EM


To make things even more simpler CSS3 has introduced rem unit (short for "root em") which is
always relative to the font-size of the root element (html), regardless of where the element lies
in the document (unlike em which is relative to parent element's font size).

This means that 1rem is equivalent to the font size of the html element, which is 16px by default
in most browsers. Let's try out an example to understand how it actually works:

Example
Try this code »
html {
font-size: 62.5%; /* font-size 1em = 10px */
}
p {
font-size: 1.4rem; /* 1.4rem = 14px */
}
p span {
font-size: 2rem; /* 2rem = 20px (not 28px) */
}

Setting Font Size with Keywords


CSS provide several keywords that you can use to define font sizes.

An absolute font size can be specified using one of the following keywords: xx-small, x-
small, small, medium, large, x-large, xx-large. Whereas, a relative font size can be specified using
the keywords: smaller or larger. Let's try out an example and see how it works:

Example
Try this code »
body {
font-size: large;
}
h1 {
font-size: larger;
}
p {
font-size: smaller;
}
Note: The keyword medium is equivalent to the browsers default font-size, which is normally
16px. Likewise, xx-small is the equivalent of 9 pixels, x-small is 10 pixels, small is 13 pixels,
large is 18 pixels, x-large is 24 pixels, and xx-large is 32 pixels.

Tip: By setting a font size on the body element, you can set the relative font sizing everywhere
else on the page, giving you the ability to easily scale the font size up or down accordingly.

Setting Font Size with Viewport Units


The font sizes can be specified using viewport units such as vw or vh.

Viewport units refer to a percentage of the browser's viewport dimensions, where 1vw = 1%
of viewport width, and 1vh = 1% of viewport height. Hence, if the viewport is 1600px wide,
1vw is 16px.

Try out the following example by resizing the browser window and see how it works:

Example
Try this code »
body {
font-size: 1vw;
}
h1 {
font-size: 3vw;
}
However, there is a problem with the viewport units. On small screens fonts become so small
that they are hardly readable. To prevent this you can utilize CSS calc() function, like this:

Example
Try this code »
html {
font-size: calc(1em + 1vw);
}
h1 {
font-size: 3rem;
}
In this example, even if the viewport width becomes 0, the font-size would be at least 1em or
16px. You further utilize CSS media queries to create better responsive and fluid typography.

Font Weight
The font-weight property specifies the weight or boldness of the font.
This property can take one of the following
values: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900 and inherit.

 The numeric values 100-900 specify the font weights, where each number represents a
weight greater than its predecessor. 400 is same as normal & 700 is same as bold.
 The bolder and lighter values are relative to the inherited font weight, while the other
values such as normal and bold are absolute font weights.

Let's try out an example to understand how this property basically works:

Example
Try this code »
p {
font-weight: bold;
}
Note: Most of the fonts are only available in a limited number of weights; often they are
available only in normal and bold. In case, if a font is not available in the specified weight, an
alternate will be chosen that is the closest available weight.

Font Variant
The font-variant property allows the text to be displayed in a special small-caps variation.
Small-caps or small capital letters are slightly different to normal capital letters, in which
lowercase letters appear as smaller versions of the corresponding uppercase letters.

Try out the following example to understand how this property actually works:

Example
Try this code »
p {
font-variant: small-caps;
}
The value normal removes small caps from the text which is already formatted that way.

CSS Text
Formatting Text with CSS
CSS provides several properties that allows you to define various text styles such as color,
alignment, spacing, decoration, transformation, etc. very easily and effectively.
The commonly used text properties are: text-align, text-decoration, text-transform, text-
indent, line-height, letter-spacing, word-spacing, and more. These properties give you precise
control over the visual appearance of the characters, words, spaces, and so on.

Let's see how to set these text properties for an element in more detail.

Text Color
The color of the text is defined by the CSS color property.

The style rule in the following example will define the default text color for the page

Example
Try this code »
body {
color: #434343;
}
Although, the color property seems like it would be a part of the CSS text, but it is actually a
standalone property in CSS. See the tutorial on CSS color to learn more about the color
property.

Text Alignment
The text-align property is used to set the horizontal alignment of the text. Text can be aligned
in four ways: to the left, right, centre or justified (straight left and right margins). Let's take a
look at an example to understand how this property basically works.

Example
Try this code »
h1 {
text-align: center;
}
p {
text-align: justify;
}
Note: When text-align is set to justify, each line is stretched so that every line has equal
width (except the last line), and the left and right margins are straight. This alignment is
generally used in publications such as magazines and newspapers.

Let's take a look at the following illustration to understand what these values actually mean.
Text Decoration
The text-decoration property is used to set or remove decorations from text. This property
typically accepts one of the following values: underline, overline, line-through, and none. You
should avoid underline text that is not a link, as it might confuse the visitor. Let's try out the
following example to understand how it basically works:

Example
Try this code »
h1 {
text-decoration: overline;
}
h2 {
text-decoration: line-through;
}
h3 {
text-decoration: underline;
}

Removing the Default Underline from Links


The text-decoration property is extensively used to remove the default underline from
the HTML hyperlinks. You can further provide some other visual cues to make it stand out
from the normal text, for example, using dotted border instead of solid underline.

Let's take a look at the following example to understand how it basically works:

Example
Try this code »
a {
text-decoration: none;
border-bottom: 1px dotted;
}
Note: When you create an HTML link, browsers built in style sheet automatically underline it
and applies a blue color, so that the readers can clearly see which text is clickable.

Text Transformation
The text-transform property is used to set the cases for a text. Text are often written in mixed
case. However, in certain situations you may want to display your text in entirely different
case. Using this property you can change an element's text content into uppercase or
lowercase letters, or capitalize the first letter of each word without modifying the original text.

Let's try out the following example to understand how it basically works:

Example
Try this code »
h1 {
text-transform: uppercase;
}
h2 {
text-transform: capitalize;
}
h3 {
text-transform: lowercase;
}

Text Indentation
The text-indent property is used to set the indentation of the first line of text within a block of
text. It is typically done by inserting the empty space before the first line of text. The size of
the indentation can be specified using percentage (%), length values in pixels, ems, etc. The
following style rule will indent the first line of the paragraphs by 100 pixels.

Example
Try this code »
p {
text-indent: 100px;
}
Note: Whether the text is indented from the left or from the right depends on the direction of
text inside the element, defined by the CSS direction property.

Letter Spacing
The letter-spacing property is used to set extra spacing between the characters of text.
This property can take a length value in pixels, ems, etc. It may also accept negative values.
When setting letter spacing, a length value indicates spacing in addition to the default inter-
character space.

Let's check out the following example to understand how it really works:

Example
Try this code »
h1 {
letter-spacing: -3px;
}
p {
letter-spacing: 10px;
}

Word Spacing
The word-spacing property is used to specify additional spacing between the words. This
property can accept a length value in pixels, ems, etc. Negative values are also allowed. Let's
try out the following example to understand how this property works:

Example
Try this code »
p.normal {
word-spacing: 20px;
}
p.justified {
word-spacing: 20px;
text-align: justify;
}
p.preformatted {
word-spacing: 20px;
white-space: pre;
}
Note: Word spacing can be affected by text justification. Also, even though whitespace is
preserved, spaces between words are affected by the word-spacing property.

Line Height
The line-height property is used to set the height of the text line. It is also called leading and
commonly used to set the distance between lines of text. The value of this property can be a
number, a percentage (%), or a length in pixels, ems, etc.
Example
Try this code »
p {
line-height: 1.2;
}
When the value is a number, the line height is calculated by multiplying the element's font
size by the number. While, percentage values are relative to the element's font size.

Note: Negative values for the line-height property are not allowed. This property is also a
component of the CSS font shorthand property.

If the value of the line-height property is greater than the value of the font-size for an
element, this difference (called the "leading") is cut in half (called the "half-leading") and
distributed evenly on the top and bottom of the in-line box. Let's check out an example:

Example
Try this code »
p {
font-size: 14px;
line-height: 20px;
background-color: #f0e68c;
}
See the tutorial on CSS3 text overflow in the advanced section to learn how to handle
overflowed text. Also see the CSS3 text shadow section to learn how to apply shadow effect
on text.

CSS Links. Styling Links with CSS


Links or hyperlinks are an essential part of a website. It allows visitors to navigate through the
site. Therefore styling the links properly is an important aspect of building a user-friendly
website. A link has four different states — link, visited, active and hover. These four states
of a link can be styled differently through using the following anchor pseudo-class selectors.

 a:link — define styles for normal or unvisited links.


 a:visited — define styles for links that the user has already visited.
 a:hover — define styles for a link when the user place the mouse pointer over it.
 a:active — define styles for links when they are being clicked.

You can specify any CSS property you'd like e.g. color, font, background, border, etc. to each
of these selectors to customize the style of links, just like you do with the normal text.
Example
Try this code »
a:link { /* unvisited link */
color: #ff0000;
text-decoration: none;
border-bottom: 1px solid;
}
a:visited { /* visited link */
color: #ff00ff;
}
a:hover { /* mouse over link */
color: #00ff00;
border-bottom: none;
}
a:active { /* active link */
color: #00ffff;
}
The order in which you are setting the style for different states of links is important, because
what defines last takes precedence over the style rules defined earlier.

Note: In general, the order of the pseudo classes should be the following —
:link, :visited, :hover, :active, :focus in order for these to work properly.

Modifying Standard Link Styles


In all major web browsers such as Chrome, Firefox, Safari, etc. links on the web pages have
underlines and uses the browser's default link colors, if you do not set the styles exclusively
for them. By default, text links will appear as follow in most of the browsers:

 An unvisited link as underlined blue text.


 A visited link as underlined purple text.
 An active link as underlined red text.

However, there is no change in the appearance of link in case of the hover state. It remains
blue, purple or red depending on which state (i.e. unvisited, visited or active) they are in. Now
let's see how to customize the links by overriding its default styling.

Setting Custom Color of Links


Simply use the CSS color property to define the color of your choice for different state of a
link. But when choosing colors make sure that user can clearly differentiate between normal
text and links. Let's try out the following example to understand how it basically works:
Example
Try this code »
a:link {
color: #1ebba3;
}
a:visited {
color: #ff00f4;
}
a:hover {
color: #a766ff;
}
a:active {
color: #ff9800;
}

Removing the Default Underline from Links


If you don't like the default underline on links, you can simply use the CSS text-
decoration property to get rid of it. Alternatively, you can apply other styling on links like
background color, bottom border, bold font, etc. to make it stand out from the normal text a
little better. The following example shows how to remove or set underline for different states
of a link.

Example
Try this code »
a:link, a:visited {
text-decoration: none;
}
a:hover, a:active {
text-decoration: underline;
}

Making Text Links Look Like Buttons


You can also make your ordinary text links look like button using CSS. To do this we need to
utilize few more CSS properties such as background-color, border, display, padding, etc. You
will learn about these properties in detail in upcoming chapters. Let's check out the following
example and see how it really works:

Example
Try this code »
a:link, a:visited {
color: white;
background-color: #1ebba3;
display: inline-block;
padding: 10px 20px;
border: 2px solid #099983;
text-decoration: none;
text-align: center;
font: 14px Arial, sans-serif;
}
a:hover, a:active {
background-color: #9c6ae1;
border-color: #7443b6;
}

CSS Lists. Types of HTML Lists


There are three different types of list in HTML:

 Unordered lists — A list of items, where every list items are marked with bullets.
 Ordered lists — A list of items, where each list items are marked with numbers.
 Definition list — A list of items, with a description of each item.

See the tutorial on HTML lists to learn more about the lists and how to create them.

Styling Lists with CSS


CSS provides the several properties for styling and formatting the most commonly used
unordered and ordered lists. These CSS list properties typically allow you to:

 Control the shape or appearance of the marker.


 Specify an image for the marker rather than a bullet point or number.
 Set the distance between a marker and the text in the list.
 Specify whether the marker would appear inside or outside of the box containing the list
items.

In the following section we will discuss the properties that can be used to style HTML lists.

Changing the Marker Type of Lists


By default, items in an ordered list are numbered with Arabic numerals (1, 2, 3, 5, and so on),
whereas in an unordered list, items are marked with round bullets (•).

But, you can change this default list marker type to any other type such as roman numerals,
latin letters, circle, square, and so on using the list-style-type property.
Let's try out the following example to understand how this property actually works:

Example
Try this code »
ul {
list-style-type: square;
}
ol {
list-style-type: upper-roman;
}

Changing the Position of List Markers


By default, markers of each list items are positioned outside of their display boxes.

However, you can also position these markers or bullet points inside of the list item's display
boxes using the list-style-position property along with the value inside. In this case the lines
will wrap under the marker instead of being indented. Here's an example:

Example
Try this code »
ol.in li {
list-style-position: inside;
}
ol.out li {
list-style-position: outside;
}
Let's take a look at the following illustration to understand how markers or bullets are
positioned.

Using Images as List Markers


You can also set an image as a list marker using the list-style-image property.
The style rule in the following example assigns a transparent PNG image "arrow.png" as the
list marker for all the items in the unordered list. Let's try it out and see how it works:

Example
Try this code »
ul li {
list-style-image: url("images/bullet.png");
}
Sometimes, the list-style-image property may not produce the expected output. Alternatively,
you can use the following solution for better control over the positioning of image markers.

As a work-around, you can also set image bullets via the background-image CSS property. First,
set the list to have no bullets. Then, define a non-repeating background image for the list
element.

The following example displays the image markers equally in all browsers:

Example
Try this code »
ul {
list-style-type: none;
}
ul li {
background-image: url("images/bullet.png");
background-position: 0px 5px; /* X-pos Y-pos (from top-left) */
background-repeat: no-repeat;
padding-left: 20px;
}

Setting All List Properties At Once


The list-style property is a shorthand property for defining all the three properties list-style-
type, list-style-image, and list-style-position of a list in one place.

The following style rule sets all the list properties in a single declaration.

Example
Try this code »
ul {
list-style: square inside url("images/bullet.png");
}
Note: When using the list-style shorthand property, the orders of the values are: list-style-
type | list-style-position | list-style-image. It does not matter if one of the values above is
missing as long as the rest are in the specified order.

Creating Navigation Menus Using Lists


HTML lists are frequently used to create horizontal navigation bar or menu that typically
appear at the top of a website. But since the list items are block elements, so to display them
inline we need to use the CSS display property. Let's try out an example to see how it really
works:

Example
Try this code »
ul {
padding: 0;
list-style: none;
background: #f2f2f2;
}
ul li {
display: inline-block;
}
ul li a {
display: block;
padding: 10px 25px;
color: #333;
text-decoration: none;
}
ul li a:hover {
color: #fff;
background: #939393;
}

CSS Tables. Styling Tables with CSS


Tables are typically used to display tabular data, such as financial reports. But when you create
an HTML table without any styles or attributes, browsers display them without any border.
With CSS you can greatly improve the appearance your tables. CSS provides several
properties that allow you to control the layout and presentation of the table elements. In the
following section you will see how to use CSS to create elegant and consistent tables.

Adding Borders to Tables


The CSS border property is the best way to define the borders for the tables.

The following example will set a black border for the <table>, <th>, and <td> elements.
Example
Try this code »
table, th, td {
border: 1px solid black;
}
By default, browser draws a border around the table, as well as around all the cells, with some
space in-between, which results in double border. To get rid of this double border problem
you can simply collapse the adjoining table cell borders and create clean single line borders.

Let's take a look at the following illustration to understand how a border is applied to a table.

Collapsing Table Borders


There are two distinct models for setting borders on table cells in CSS: separate and collapse.

In the separate border model, which is the default, each table cell has its own distinct borders,
whereas in the collapsed border model, adjacent table cells share a common border. You can
set the border model for an HTML table by using the CSS border-collapse property.

The following style rules will collapse the table cell borders and apply one pixel black border.

Example
Try this code »
table {
border-collapse: collapse;
}
th, td {
border: 1px solid black;
}
Note: You can also remove the space between the table cell borders through setting the
value of CSS border-spacing property to 0. However, it only removes the space but do not
merge the borders like when you set the border-collapse to collapse.

Adjusting Space inside Tables


By default, the browser creates the table cells just large enough to contain the data in the
cells. To add more space between the table cell contents and the cell borders, you can simply
use the CSS padding property. Let's try out the following example and see how it works:

Example
Try this code »
th, td {
padding: 15px;
}
You can also adjust the spacing between the borders of the cells using the CSS border-
spacing property, if the borders of your table are separated (which is default).

The following style rules apply the spacing of 10 pixels between all borders within a table:

Example
Try this code »
table {
border-spacing: 10px;
}

Setting Table Width and Height


By default, a table will render just wide and tall enough to contain all of its contents. But, you
can also set the width and height of the table as well as its cells explicitly using
the width and height CSS property. The style rules in the following example will sets the
width of the table to 100%, and the height of the table header cells to 40px.

Example
Try this code »
table {
width: 100%;
}
th {
height: 40px;
}
Controlling the Table Layout
A table expands and contracts to accommodate the data contained inside it. This is the
default behavior. As data fills inside the table, it continues to expand as long as there is space.
Sometimes, however, it is necessary to set a fixed width for the table in order to manage the
layout. You can do this with the help of CSS table-layout property. This property defines the
algorithm to be used to layout the table cells, rows, and columns. This property takes one of
two values:

 auto — Uses an automatic table layout algorithm. With this algorithm, the widths of the
table and its cells are adjusted to fit the content. This is the default value.
 fixed — Uses the fixed table layout algorithm. With this algorithm, the horizontal layout of
the table does not depend on the contents of the cells; it only depends on the table's
width, the width of the columns, and borders or cell spacing. It is normally faster than auto.

The style rules in the following example specify that the HTML table is laid out using the fixed
layout algorithm and has a fixed width of 300 pixels. Let's try it out and see how it works:

Example
Try this code »
table {
width: 300px;
table-layout: fixed;
}
Tip: You can optimize the table rendering performance by specifying the value fixed for
the table-layout property. Fixed value of this property causes the table to be rendered one
row at a time, providing users with information at a faster pace.

Note: Without fixed value of the table-layout property on large tables, users won't see any
part of the table until the browser has rendered the whole table.

Aligning the Text Inside Table Cells


You can align text content inside the table cells either horizontally or vertically.

Horizontal Alignment of Cell Contents


For horizontal alignment of text inside the table cells you can use the text-align property in
the same way as you use with other elements. You align text to either left, right, center or
justify. The following style rules will left-align the text inside the <th> elements.
Example
Try this code »
th {
text-align: left;
}
Note: Text inside the <td> elements are left-aligned by default, whereas the text inside
the <th> elements are center-aligned and rendered in bold font by default.

Vertical Alignment of Cell Contents


Similarly, you can vertically align the content inside the <th> and <td> elements to top,
bottom, or middle using the CSS vertical-align property. The default vertical alignment is
middle.

The following style rules will vertically bottom-align the text inside the <th> elements.

Example
Try this code »
th {
height: 40px;
vertical-align: bottom;
}

Controlling the Position of Table Caption


You can set the vertical position of a table caption using the CSS caption-side property.

The caption can be placed either at the top or bottom of the table. The default position is top.

Example
Try this code »
caption {
caption-side: bottom;
}
Tip: To change the horizontal alignment of the table's caption text (e.g. left or right), you can
simply use the CSS text-align property, like you do with normal text.

Handling Empty Cells


In tables that uses separate border model, which is default, you can also control the rendering
of the cells that have no visible content using the empty-cells CSS property.
This property accepts a value of either show or hide. The default value is show, which renders
empty cells like normal cells, but if the value hide is specified no borders or backgrounds are
drawn around the empty cells. Let's try out an example to understand how it really works:

Example
Try this code »
table {
border-collapse: separate;
empty-cells: hide;
}
Note: Placing a non-breaking space (&nbsp;) inside a table cell make it non-empty. Therefore,
even if that cell looks empty the hide value will not hide the borders and backgrounds.

Creating Zebra-striped Tables


Setting different background colors for alternate rows is a popular technique to improve the
readability of tables that has large amount of data. This is commonly known as zebra-striping
a table. You can simply achieve this effect by using the CSS :nth-child() pseudo-
class selector. The following style rules will highlight every odd rows within the table body.

Example
Try this code »
tbody tr:nth-child(odd) {
background-color: #f2f2f2;
}
A zebra-striped table typically looks something like the following picture.

Note: The :nth-child() pseudo-class select elements based on their position in a group of
siblings. It can take a number, a keyword even or odd, or an expression of the form xn+y
where x and y are integers (e.g. 1n, 2n, 2n+1, ...) as an argument.
Making a Table Responsive
Tables are not responsive in nature. However, to support mobile devices you can add
responsiveness to your tables by enabling horizontal scrolling on small screens. To do this
simply wrap your table with a <div> element and apply the style overflow-x: auto; as shown
below:

Example
Try this code »
<div style="overflow-x: auto;">
<table>
... table content ...
</table>
</div>

CSS Box Model. What is Box Model?


Every element that can be displayed on a web page is comprised of one or more rectangular
boxes. CSS box model typically describes how these rectangular boxes are laid out on a web
page. These boxes can have different properties and can interact with each other in different
ways, but every box has a content area and optional surrounding padding, border,
and margin areas. The following diagram shows how the width, height, padding, border, and
margin CSS properties determines how much space an element can take on a web page.
Padding is the transparent space between the element's content and its border (or edge of
the box, if it has no border), whereas margin is the transparent space around the border.

Also, if an element has the background color it will be visible through its padding area. The
margin area is always remain transparent, it is not affected by the element's background color,
however, it causes the background color of the parent element to be seen through it.

Width and Height of the Elements


Usually when you set the width and height of an element using the
CSS width and height properties, in reality you are only setting the width and height of the
content area of that element. The actual width and height of the element's box depends on
the several factors.

The actual space that an element's box might take on a web page is calculated like this:

Box Size CSS Properties

Total Width width + padding-left + padding-right + border-left + border-right + margin-left +


margin-right

Total Height height + padding-top + padding-bottom + border-top + border-bottom + margin-top +


margin-bottom

You will learn about each of these CSS properties in detail in upcoming chapters.

Now let's try out the following example to understand how the box model actually works:

Example
Try this code »
div {
width: 300px;
height: 200px;
padding: 15px; /* set padding for all four sides */
border: 10px solid black; /* set border for all four sides */
margin: 20px auto; /* set top and bottom margin to 20 pixels, and left
and right margin to auto */
}
Note: In CSS box model; the content area of an element's box is the area where its content,
e.g., text, image, video, etc. appears. It may also contain descendant elements boxes.

CSS Dimension. Setting Element Dimensions


CSS has several dimension properties, such as width, height, max-width, min-width, max-height,
and min-height that allows you to control the width and height of an element. The following
sections describe how to use these properties to create a better web page layout.

Setting the Width and Height


The width and height property defines the width and height of the content area of an element.

This width and height does not include paddings, borders, or margins. See the CSS box
model to know how the effective width and height of an element's box is calculated.

Let's try out the following example and see how it actually works:

Example
Try this code »
div {
width: 300px;
height: 200px;
}
The above style rules assigns a fixed width of 300 pixels and height of 200px to
the <div> element. The width and height properties can take the following values:

 length - specifies a width in px, em, rem, pt, cm, etc.


 % - specifies a width in percentage (%) of the width of the containing element.
 auto - the browser calculates a suitable width for the element.
 initial - Sets the width and height to its default value, which is auto.
 inherit - specifies that the width should be inherited from the parent element.

You can not specify negative values to the width and height properties.

Tip: Typically when you create a block element, such as <div>, <p>, etc. browser automatically
set their width to 100% of the available width, and height to whatever is needed to show all
the content. You should avoid setting a fixed width and height unless it is necessary.

Setting Maximum Width and Height


You can use the max-width and max-height property to specify the maximum width and height of
the content area. This maximum width and height does not include paddings, borders, or
margins.
An element cannot be wider than the max-width value, even if the width property value is set to
something larger. For instance, if the width is set to 300px and the max-width is set to 200px, the
actual width of the element will be 200px. Let's check out an example:

Example
Try this code »
div {
width: 300px;
max-width: 200px;
}
Note: If the min-width property is specified with a value greater than that of max-width property,
in this case the min-width value will in fact be the one that's applied.

Likewise, an element that has max-height applied will never be taller than the value specified,
even if the height property is set to something larger. For example, if the height is set to 200px
and the max-height set to 100px, the actual height of the element will be 100px.

Example
Try this code »
div {
height: 200px;
max-height: 100px;
}
Note: If the min-height property is specified with a value greater than that of max-
height property, in this case the min-height value will in fact be the one that's applied.

Setting Minimum Width and Height


You can use the min-width and min-height property specify the minimum width and height of
the content area. This minimum width and height does not include paddings, borders, or
margins. An element cannot be narrower than the min-width value, even if the width property
value is set to something lesser. For example, if the width is set to 300px and the min-width is
set to 400px, the actual width of the element will be 400px. Let's see how it actually works:

Example
Try this code »
div {
width: 200px;
min-width: 300px;
}
Note: The min-width property is usually used to ensure that an element has at least a minimum
width even if no content is present. However the element will be allowed to grow normally if
its content exceeds the minimum width set.

Similarly, an element to which min-height is applied will never be smaller than the value
specified, even if the height property is set to something lesser. For example, if the height is set
to 200px, and the min-height is set to 300px, the actual height of the element will be 300px.

Example
Try this code »
div {
height: 100px;
min-height: 200px;
}
Note: The min-height property is usually used to ensure that an element has at least a
minimum height even if no content is present. However the element will be allowed to grow
normally if the content exceeds the minimum height set.

Setting a Width and Height Range


The min-width and min-height properties are often used in combination with the max-
width and max-height properties to produce a width and height range for an element.

This can be very useful for creating flexible design. In the following example the minimum
width of the <div> element would be 300px and it can stretches horizontally up to a maximum
500px.

Example
Try this code »
div {
min-width: 300px;
max-width: 500px;
}
Similarly, you can define a height range for an element. In the example below the minimum
height of the <div> element would be 300px and it can stretches vertically up to a maximum
500px.

Example
Try this code »
div {
min-height: 300px;
max-height: 500px;
}

CSS Padding. CSS Padding Properties


The CSS padding properties allow you to set the spacing between the content of an element
and its border (or the edge of the element's box, if it has no defined border). The padding is
affected by the element's background-color. For instance, if you set the background color for
an element it will be visible through the padding area.

Define Paddings for Individual Sides


You can specify the paddings for the individual sides of an element such as top, right, bottom,
and left sides using the CSS padding-top, padding-right, padding-bottom, and the padding-
left properties, respectively. Let's try out an example to understand how it works:

Example
Try this code »
h1 {
padding-top: 50px;
padding-bottom: 100px;
}
p {
padding-left: 75px;
padding-right: 75px;
}
The padding properties can be specified using the following values:

 length - specifies a padding in px, em, rem, pt, cm, etc.


 % - specifies a padding in percentage (%) of the width of the containing element.
 inherit - specifies that the padding should be inherited from the parent element.

Unlike CSS margin, values for the padding properties cannot be negative.

The Padding Shorthand Property


The padding property is a shorthand property to avoid setting padding of each side
separately, i.e., padding-top, padding-right, padding-bottom and padding-left.

Let's take a look at the following example to understand how it basically works:

Example
Try this code »
h1 {
padding: 50px; /* apply to all four sides */
}
p {
padding: 25px 75px; /* vertical | horizontal */
}
div {
padding: 25px 50px 75px; /* top | horizontal | bottom */
}
pre {
padding: 25px 50px 75px 100px; /* top | right | bottom | left */
}
This shorthand notation can take one, two, three, or four whitespace separated values.

 If one value is specified, it is applied to all four sides.


 If two values are specified, the first value is applied to the top and bottom side, and the
second value is applied to the right and left side of the element's box.
 If three values are specified, the first value is applied to the top, second value is applied
to right and left side, and the last value is applied to the bottom.
 If four values are specified, they are applied to the top, right, bottom and the left side of
the element's box respectively in the specified order.

It is recommended to use the shorthand properties, it will help you to save some time by
avoiding the extra typing and make your CSS code easier to follow and maintain.

Effect of Padding and Border on Layout


When creating web page layouts, adding a padding or border to the elements sometimes
produce unexpected result, because padding and border is added to the width and height of
the box generated by the element, as you have learnt in the CSS box model chapter.

For instance, if you set the width of a <div> element to 100% and also apply left right padding
or border on it, the horizontal scrollbar will appear. Let's see an example:

Example
Try this code »
div {
width: 100%;
padding: 25px;
}
To prevent padding and border from changing element's box width and height, you can use
the CSS box-sizing property. In the following example the width and height of the <div> box
will remain unchanged, however, its content area will decrease with increasing padding or
border.
Example
Try this code »
div {
width: 100%;
padding: 25px;
box-sizing: border-box;
}
You will learn about the CSS box sizing feature in detail in the upcoming chapters.

CSS Border. CSS Border Properties


The CSS border properties allow you to define the border area of an element's box.

Borders appear directly between the margin and padding of an element. The border can
either be a predefined style like, solid line, dotted line, double line, etc. or an image.

The following section describes how to set the style, color, and width of the border.

Understanding the Different Border Styles


The border-style property sets the style of a box's border such as: solid, dotted, etc. It is a
shorthand property for setting the line style for all four sides of the elements border.

The border-style property can have the following


values: none, hidden, solid, dashed, dotted, double, inset, outset, groove, and ridge. Now,
let's take a look at the following illustration, it gives you a sense of the differences between
the border style types.
The values none and hidden displays no border, however, there is a slight difference between
these two values. In the case of table cell and border collapsing, the none value has
the lowest priority, whereas the hidden value has the highest priority, if any other conflicting
border is set. The values inset, outset, groove, and ridge creates a 3D like effect which
essentially depends on the border-color value. This is typically achieved by creating a
"shadow" from two colors that are slightly lighter and darker than the border color. Let's
check out an example:

Example
Try this code »
h1 {
border-style: dotted;
}
p {
border-style: ridge;
}
Note: You must specify a border style in order to make the border appear around an element,
because the default border style is none. Whereas, the default border width or thickness
is medium, and the default border color is the same as the text color.

Setting the Border Width


The border-width property specifies the width of the border area. It is a shorthand property
for setting the thickness of all the four sides of an element's border at the same time.

Let's try out the following example to understand how it works:

Example
Try this code »
p {
border-style: dashed;
border-width: 10px;
}
Tip: The border width can be specified using any length value, such as px, em, rem, and so on.
In addition to length units, the border width may also be specified using one of three
keywords: thin, medium, and thick. Percentage values are not allowed.

Specifying the Border Color


The border-color property specifies the color of the border area. This is also a shorthand
property for setting the color of all the four sides of an element's border.

The following style rules adds a solid border of red color around the paragraphs.
Example
Try this code »
p {
border-style: solid;
border-color: #ff0000;
}
Note: The CSS border-width or border-color property does not work if it is used alone.
Use the border-style property to set the style of the border first.

The Border Shorthand Property


The border CSS property is a shorthand property for setting one or more of the individual
border properties border-width, border-style and border-color in a single rule.

Let's take a look at the following example to understand how it works:

Example
Try this code »
p {
border: 5px solid #00ff00;
}
If the value for an individual border property is omitted or not specified while setting the
border shorthand property, the default value for that property will be used instead, if any.

For instance, if the value for the border-color property is missing or not specified when
setting the border, the element's color property will be used as the value for the border color.

In the example below, the border will be a solid red line of 5 pixels width:

Example
Try this code »
p {
color: red;
border: 5px solid;
}
But, in the case of border-style, omitting the value will cause no border to show at all,
because the default value for this property is none. In the following example, there will be no
border:

Example
Try this code »
p {
border: 5px #00ff00;
}

CSS Margin. CSS Margin Properties


The CSS margin properties allow you to set the spacing around the border of an element's
box (or the edge of the element's box, if it has no defined border). An element's margin is not
affected by its background-color, it is always transparent. However, if the parent element has
the background color it will be visible through its margin area.

Setting Margins for Individual Sides


You can specify the margins for the individual sides of an element such as top, right, bottom,
and left sides using the CSS margin-top, margin-right, margin-bottom, and the margin-
left properties, respectively. Let's try out the following example to understand how it works:

Example
Try this code »
h1 {
margin-top: 50px;
margin-bottom: 100px;
}
p {
margin-left: 75px;
margin-right: 75px;
}
The margin properties can be specified using the following values:

 length - specifies a margin in px, em, rem, pt, cm, etc.


 % - specifies a margin in percentage (%) of the width of the containing element.
 auto - the browser calculates a suitable margin to use.
 inherit - specifies that the margin should be inherited from the parent element.

You can also specify negative margins on an element, e.g., margin: -10px;, margin: -5%;,
etc.

The Margin Shorthand Property


The margin property is a shorthand property to avoid setting margin of each side separately,
i.e., margin-top, margin-right, margin-bottom and margin-left. Let's take a look at the
following example to understand how it basically works:
Example
Try this code »
h1 {
margin: 50px; /* apply to all four sides */
}
p {
margin: 25px 75px; /* vertical | horizontal */
}
div {
margin: 25px 50px 75px; /* top | horizontal | bottom */
}
hr {
margin: 25px 50px 75px 100px; /* top | right | bottom | left */
}
This shorthand notation can take one, two, three, or four whitespace separated values.

 If one value is specified, it is applied to all four sides.


 If two values are specified, the first value is applied to the top and bottom side, and the
second value is applied to the right and left side of the element's box.
 If three values are specified, the first value is applied to the top, second value is applied
to right and left side, and the last value is applied to the bottom.
 If four values are specified, they are applied to the top, right, bottom and the left side of
the element's box respectively in the specified order.

It is recommended to use the shorthand properties, it will help you to save some time by
avoiding the extra typing and make your CSS code easier to follow and maintain.

Horizontal Centering with Auto Margins


The auto value for the margin property tells the web browser to automatically calculate the
margin. This is commonly used to center an element horizontally within a larger container.

Let's try out the following example to understand how it works:

Example
Try this code »
div {
width: 300px;
background: gray;
margin: 0 auto;
}
The above style rules lets the <div> element take up 300 pixels of all the horizontal space
available, and the remaining space will be equally divided between left and right margins.
CSS Outline. CSS Outline Properties
The CSS outline properties allow you to define an outline area around an element's box.

An outline is a line that is drawn just outside the border edge of the elements. Outlines are
generally used to indicate focus or active states of the elements such as buttons, links, form
fields, etc. The following section describes how to set the style, color, and width of the outline.

Outlines Vs Borders
An outline looks very similar to the border, but it differs from border in the following ways:

 Outlines do not take up space, because they always placed on top of the box of the
element which may cause them to overlap other elements on the page.
 Unlike borders, outlines won't allow us to set each edge to a different width, or set
different colors and styles for each edge. An outline is the same on all sides.
 Outlines do not have any impact on surrounding elements apart from overlapping.
 Unlike borders, outlines do not change the size or position of the element.
 Outlines may be non-rectangular, but you cannot create circular outlines.

Note: If you put an outline on an element, it will take up the same amount of space on the
web pages as if you didn't have an outline on that element. Because it
overlap margins (transparent area outside of the border) and surrounding elements.

Understanding the Different Outline Styles


The outline-style property sets the style of an element's outline such as: solid, dotted, etc.

The outline-style property can have one of the following


values: none, solid, dashed, dotted, double, inset, outset, groove, and ridge. Now, let's take a look at
the following illustration, it gives you a sense of the differences between the outline style
types.
The value none displays no outline. The values inset, outset, groove, and ridge creates a 3D like
effect which essentially depends on the outline-color value. This is typically achieved by
creating a "shadow" from two colors that are slightly lighter and darker than the outline color.

Let's try out the following example and see how it basically works:

Example
Try this code »
h1 {
outline-style: dotted;
}
p {
outline-style: ridge;
}
Note: You must specify a outline style in order to make the outline appear around an
element, because the default outline style is none. Whereas, the default outline width or
thickness is medium, and the default outline color is the same as the text color.

Setting the Outline Width


The outline-width property specifies the width of the outline to be added on an element.

Let's try out the following example to understand how it actually works:

Example
Try this code »
p {
outline-style: dashed;
outline-width: 10px;
}
Tip: The outline width can be specified using any length value, such as px, em, rem, and so on.
It can also be specified using one of the three keywords: thin, medium, and thick. Percentage or
negative values are not allowed — just like the border-width property.

Specifying the Outline Color


The outline-color property sets the color of the outline.

This property accepts the same values as those used for the color property.

The following style rules adds a solid outline of blue color around the paragraphs.

Example
Try this code »
p {
outline-style: solid;
outline-color: #0000ff;
}
Note: The CSS outline-width or outline-color property does not work if it is used alone. Use
the outline-style property to set the style of the outline first.

The Outline Shorthand Property


The outline CSS property is a shorthand property for setting one or more of the individual
outline properties outline-style, outline-width and outline-color in a single rule.

Let's take a look at the following example to understand how it works:

Example
Try this code »
p {
outline: 5px solid #ff00ff;
}
If the value for an individual outline property is omitted or not specified while setting the
outline shorthand property, the default value for that property will be used instead, if any.

For instance, if the value for the outline-color property is missing or not specified when setting
the outlines, the element's color property will be used as the value for the outline color.

In the following example, the outline will be a solid green line of 5px width:
Example
Try this code »
p {
color: green;
outline: 5px solid;
}
But, in the case of outline-style, omitting the value will cause no outline to show at all,
because the default value for this property is none. In the example below, there will be no
outline:

Example
Try this code »
p {
outline: 5px #00ff00;
}

Removing Outline Around Active Links


The outline property is widely used to remove the outline around active links.

However, it is recommended to apply some alternative style to indicate that the link has focus.

Let's try out the following example and see how it basically works:

Example
Try this code »
a, a:active, a:focus {
outline: none;
}

CSS Cursors. Changing the Look of Cursor


The browsers typically display the mouse pointer over any blank part of a web page, the
gloved hand over any linked or clickable item and the edit cursor over any text or text field.
With CSS you can redefine those properties to display a variety of different cursors.

Example
Try this code »
h1 {
cursor: move;
}
p {
cursor: text;
}
The table below demonstrates the different cursors that most browsers will accept. Place your
mouse pointer over the "TEST" link in the output column to reveal that cursor.

Look Values Example Output

default a:hover{cursor:default;} TEST

pointer a:hover{cursor:pointer;} TEST

text a:hover{cursor:text;} TEST

wait a:hover{cursor:wait;} TEST

help a:hover{cursor:help;} TEST

progress a:hover{cursor:progress;} TEST

crosshair a:hover{cursor:crosshair;} TEST

move a:hover{cursor:move;} TEST

url() a:hover{cursor:url("custom.cur"), default;} TEST

Check out more cursors »

Creating a Customized Cursor


It is also possible to have completely customized cursors. The cursor property handles a
comma-separated list of user-defined cursors values followed by the generic cursor. If the first
cursor is specified incorrectly or can't be found, the next cursor in the comma-separated list
will be used, and so on until a usable cursor is found. If none of the user-defined cursors is
valid or supported by the browser, the generic cursor at the end of the list will be used
instead.

Tip: The standard format that can be used for cursors is the .cur format. However, you can
convert images such as .jpg and .gif into .cur format using the image converter software
freely available online.
Example
Try this code »
a {
cursor: url("custom.gif"), url("custom.cur"), default;
}
In the above example custom.gif and custom.cur is the custom cursor file, uploaded to your
server space, and default is the generic cursor that will be used if the custom cursor is missing,
or isn't supported by the viewer's browser.

Warning: If you are declaring a custom cursor, you must define a generic cursor at the end of
the list, otherwise the custom cursor will not render correctly.

Here is a live demonstration of a custom cursor.


Hover your mouse pointer over this link to reveal the custom cursor

Note: IE9 and earlier versions only support URL values of the type .cur for static cursor,
and .ani for animated cursor. However, browsers such as Firefox, Chrome and Safari have
support for .cur, .png, .gif and .jpg but not .ani.

CSS Overflow. Handling Overflowing Content


There may be a situation when the content of an element might be larger than the
dimensions of the box itself. For example given width and height properties did not allow
enough room to accommodate the content of the element. CSS overflow property allowing
you to specify whether to clip content, render scroll bars or display overflow content of
a block-level element. This property can take one of the following
values: visible (default), hidden, scroll, and auto. CSS3 also defines the overflow-
x and overflow-y properties which allow for independent control of the vertical and
horizontal clipping.

Example
Try this code »
div {
width: 250px;
height: 150px;
overflow: scroll;
}
Value Description

visible The default value. Content is not clipped; it will be rendered outside the element's box, and may
thus overlap other content.
hidden Content that overflows the element's box is clipped and the rest of the content will be invisible.

scroll The overflowing content is clipped, just like hidden, but provides a scrolling mechanism to access
the overflowed content.

auto If content overflows the element's box it will automatically provides the scrollbars to see the rest of
the content, otherwise scrollbar will not appear.

CSS Units. Understanding CSS Units


The units in which length is measured can be either absolute such as pixels, points and so on,
or relative such as percentages (%) and em units. Specifying CSS units is obligatory for non-zero
values, because there is no default unit. Missing or ignoring a unit would be treated as an
error. However, if the value is 0, the unit can be omitted (after all, zero pixels is the same
measurement as zero inches).

Note: Lengths refer to distance measurements. A length is a measurement comprising a


numeric value and a unit only such as 10px, 2em, 50% etc. The whitespace can't appear between
the number and the unit.

Relative Length Units


Relative length units specify a length relative to another length property. Relative units are:

Unit Description

em the current font-size

ex the x-height of the current font

The em and ex units depend on the font size that's applied to the element.

Using the Em Unit


A measurement of 1em is equal to the computed value of the font-size property of the element
on which it is used. It may be used for vertical or horizontal measurement.

For example, if font-size of the element set to 16px and line-height set to 2.5em then the
calculated value of line-height in pixel is 2.5 x 16px = 40px.
Example
Try this code »
p {
font-size: 16px;
line-height: 2.5em;
}
The exception occurs when em is specified in the value of font-size property itself, in that case
it refers to the font size of the parent element. So, when we specify a font size in em, 1em is
equal to the inherited font-size. As such, font-size: 1.2em; makes the text 1.2 times larger than
the parent element's text.

Example
Try this code »
body {
font-size: 62.5%;
font-family: Arial, Helvetica, sans-serif;
}
p {
font-size: 1.6em;
}
p:firt-letter {
font-size: 3em;
font-weight: bold;
}
Let's understand what this code was all about. The default size for the fonts in all modern
browsers is 16px. Our first step is to reduce this size for the entire document by setting the
body font-size to 62.5%, which resets the font-size to 10px (62.5% of 16px).

This is to round off the default font-size for easy px to em conversion.

Using the Ex Unit


The ex unit is equal to the x-height of the current font.

The x-height is so called because it is often equal to the height of the lowercase 'x', as
illustrated below. However, an ex is defined even for fonts that do not contain an 'x'.
Absolute Length Units
Absolute length units are fixed in relation to each other. They are highly dependent on the
output medium, so are mainly useful when the output environment is known. The absolute
units consist of the physical units (in, cm, mm, pt, pc) and the px unit.

Unit Description

in inches – 1in is equal to 2.54cm.

cm centimeters.

mm millimeters.

pt points – In CSS, one point is defined as 1/72 inch (0.353mm).

pc picas – 1pc is equal to 12pt.

px pixel units – 1px is equal to 0.75pt.

Absolute physical units such as in, cm, mm, etc. should be used for print media and similar high-
resolution devices. Whereas, for on-screen display such as desktop and lower-resolution
devices, it is recommended to use the pixel or em units.

Example
Try this code »
h1 { margin: 0.5in; } /* inches */
h2 { line-height: 3cm; } /* centimeters */
h3 { word-spacing: 4mm; } /* millimeters */
h4 { font-size: 12pt; } /* points */
h5 { font-size: 1pc; } /* picas */
h6 { font-size: 12px; } /* picas */
Tip: Style sheets that use the relative units such as em or percentage (%) can more easily scale
from one output environment to another.

CSS Visual Formatting. CSS Visual Formatting


Model
The CSS visual formatting model is the algorithm that is used to process the documents for
visual media. In the visual formatting model, each element in the document tree generates
zero or more boxes according to the box model.
The layout of these boxes is depends on the following factors:

 box dimensions.
 type of the element (block or inline).
 positioning scheme (normal flow, float, and absolute positioning).
 relationships between elements in the document tree.
 external information e.g. viewport size, built-in dimensions of images, etc.

Note: The document tree is the hierarchy of elements encoded in the source document. Every
element in the document tree has exactly one parent, with the exception of the root element,
which has none.

Type of Boxes Generated in CSS


Every element displayed on a web page generates a rectangular box. The following section
describes the types of boxes that may be generated by an element.

Block-level Elements and Block Boxes


Block-level elements are those elements that are formatted visually as blocks (i.e. takes up the
full width available), with a line break before and after the element. For example, paragraph
element (<p>), headings (<h1> to <h6>), divisions (<div>) etc. Generally, block-level elements may
contain inline elements and other block-level elements.

Inline-level Elements and Inline Boxes


Inline-level elements are those elements of the source document that do not form new blocks
of content; the content is distributed in lines. For example, emphasized pieces of text within a
paragraph (<em>), spans (<span>), strong element (<strong>) etc.

Inline elements typically may only contain text and other inline elements.

Note: Unlike block-level elements, an inline-level element only takes up as much width as
necessary, and does not force line breaks.

You can change how an element will be displayed on a web page using the CSS display
property. You will learn about the display property in next chapter.

CSS Display. CSS Display Property


The CSS specification defines the default display value for all the elements, e.g.
the <div> element is rendered as block, while the <span> element is displayed inline.
Changing the Default Display Value
Overriding the default display value of an element is an important implication of
the display property. For example, changing an inline-level element to be displayed as block-
level element or changing the block-level element to be displayed as an inline-level element.

Note: The CSS display property is one of the most powerful and useful properties in all the
CSS. It can be very useful for creating web pages that looks in a different way, but still follow
the web standards.

The following section describes you the most commonly used CSS display values.

Display Block
The block value of the display property forces an element to behave like block-level element,
like a <div> or <p> element. The style rules in the following example displays
the <span> and <a> elements as block-level elements:

Example
Try this code »
span {
display: block;
}
a {
display: block;
}
Note: Changing the display type of an element only changes the display behavior of an
element, NOT the type of element it is. For example, an inline element set to display:
block; is not allowed to have a block element nested inside of it.

Display Inline
The inline value of the display property causes an element to behave as though it were
an inline-level element, like a <span> or an <a> element. The style rules in the following
example displays the <p> and <li> elements as inline-level elements:

Example
Try this code »
p {
display: inline;
}
ul li {
display: inline;
}

Display Inline-Block
The inline-block value of the display property causes an element to generate a block box
that will be flowed with surrounding content i.e. in the same line as adjacent content. The
following style rules displays the <div> and <span> elements as inline-block:

Example
Try this code »
div {
display: inline-block;
}
span {
display: inline-block;
}

Display None
The value none simply causes an element to generate no boxes at all. Child elements do not
generate any boxes either, even if their display property is set to something other than none.
The document is rendered as though the element did not exist in the document tree.

Example
Try this code »
h1 {
display: none;
}
p {
display: none;
}
Note: The value none for the display property does not create an invisible box — it creates
no box at all. See the live demo given inside visibility vs display section.

CSS Visibility
The visibility property determines whether an element is visible or hidden.
Controlling the Visibility of Elements
You can use the visibility property to control whether an element is visible or not. This
property can take one of the following values listed in the table below:

Value Description

visible Default value. The box and its contents are visible.

hidden The box and its content are invisible, but still affect the layout of the page.

collapse This value causes the entire row or column to be removed from the display. This value is used for
row, row group, column, and column group elements.

inherit Specifies that the value of the visibility property should be inherited from the parent element i.e.
takes the same visibility value as specified for its parent.

The style rule visibility: collapse; however removes the internal table elements, but it does
not affect the layout of the table in any other way. The space normally occupied by the table
elements will be filled by the subsequent siblings.

Note: If the style rule visibility: collapse; is specified for other elements rather than the table
elements, it causes the same behavior as hidden.

CSS Visibility vs Display


The display and visibility CSS properties appear to be the same thing, but they are in fact
quite different and often confuse those new to web development.

 visibility: hidden; hides the element, but it still takes up space in the layout. Child
element of a hidden box will be visible if their visibility is set to visible.
 display: none; turns off the display and removes the element completely from the
document. It does not take up any space, even though the HTML for it is still in the source
code. All child elements also have their display turned off, even if their display property is
set to something other than none.

Check out the following demo to find out how display and visibility affect the layouts.
CSS Position. CSS Positioning Methods
Positioning elements appropriately on the web pages is a necessity for a good layout design.
There are several methods in CSS that you can use for positioning elements. The following
section will describe you these positioning methods one by one.

Static Positioning
A static positioned element is always positioned according to the normal flow of the page.
HTML elements are positioned static by default. Static positioned elements are not affected by
the top, bottom, left, right, and z-index properties.

Example
Try this code »
.box {
padding: 20px;
background: #7dc765;
}

Relative Positioning
A relative positioned element is positioned relative to its normal position. In the relative
positioning scheme the element's box position is calculated according to the normal flow.
Then the box is shifted from this normal position according to the properties —
top or bottom and/or left or right.
Example
Try this code »
.box {
position: relative;
left: 100px;
}
Note: A relatively positioned element can be moved and overlap other elements, but it keeps
the space originally reserved for it in the normal flow.

Absolute Positioning
An absolutely positioned element is positioned relative to the first parent element that has a
position other than static. If no such element is found, it will be positioned on a page relative
to the 'top-left' corner of the browser window. The box's offsets further can be specified using
one or more of the properties top, right, bottom, and left. Absolutely positioned elements
are taken out of the normal flow entirely and thus take up no space when placing sibling
elements. However, it can overlap other elements depending on the z-index property value.
Also, an absolutely positioned element can have margins, and they do not collapse with any
other margins.

Example
Try this code »
.box {
position: absolute;
top: 200px;
left: 100px;
}

Fixed Positioning
Fixed positioning is a subcategory of absolute positioning. The only difference is, a fixed
positioned element is fixed with respect to the browser's viewport and does not move when
scrolled.

Example
Try this code »
.box {
position: fixed;
top: 200px;
left: 100px;
}
Note: In case of the print media type, the fixed positioned element is rendered on every page,
and is fixed with respect to the page box (even in print-preview). IE7 and IE8 support the fixed
value only if a <!DOCTYPE> is specified.

CSS Layers
Stacking Elements in Layers Using z-index Property
Usually HTML pages are considered two-dimensional, because text, images and other
elements are arranged on the page without overlapping. However, in addition to their
horizontal and vertical positions, boxes can be stacked along the z-axis as well i.e. one on top
of the other by using the CSS z-index property. This property specifies the stack level of a box
whose position value is one of absolute, fixed, or relative.

The z-axis position of each layer is expressed as an integer representing the stacking order for
rendering. An element with a larger z-index overlaps an element with a lower one.

A z-index property can help you to create more complex webpage layouts. Following is the
example which shows how to create layers in CSS.

Example
Try this code »
.box {
position: absolute;
left: 10px;
top: 20px;
z-index: 2;
}

CSS Float. Floating Elements with CSS


You can float elements to the left or right, but only applies to the elements that generate
boxes that are not absolutely positioned. Any element that follows the floated element will
flow around the floated element on the other side.

The float property may have one of the three values:

Value Description

left The element floats on the left side of its containing block.
right The element floats on the right side of its containing block.

none Removes the float property from an element.

How Elements Float


A floated element is taken out of the normal flow and shifted to the left or right as far as
possible in the space available of the containing element. Other elements normally flow
around the floated items, unless they are prevented from doing so by their clear property.
Elements are floated horizontally, which means that an element can only be floated left or
right, not up or down.

Example
Try this code »
img {
float: left;
}
If several floating elements are placed adjacently, they will float next to each other if there is
horizontal room. If there is not enough room for the float, it is shifted downward until either it
fits or there are no more floating elements present.

Example
Try this code »
.thumbnail {
float: left;
width: 125px;
height: 125px;
margin: 10px;
}

Turning off Float Using Clear Property


Elements that comes after the floating element will flow around it. The clear property
specifies which sides of an element's box other floating elements are not allowed.

Example
Try this code »
.clear {
clear: left;
}
Note: This property can clear an element only from floated boxes within the same block. It
doesn't clear the element from floated child boxes within the element itself. To learn more
about clearing float see tutorial on CSS Alignment.

CSS Alignment. Text Alignment


Text inside the block-level elements can aligned by setting the text-align properly.

Example
Try this code »
h1 {
text-align: center;
}
p {
text-align: left;
}
See tutorial on CSS Text to learn more about text formatting.

Center Alignment Using the margin Property


Center alignment of a block-level element is one of the most important implications of the
CSS margin property. For example, the <div> container can be aligned horizontally center by
setting the left and right margins to auto.

Example
Try this code »
div {
width: 50%;
margin: 0 auto;
}
The style rules in the above example center align the <div> element horizontally.

Note: The value auto for the margin property will not work in Internet Explorer 8 and earlier
versions, unless a <!DOCTYPE> is specified.
Aligning Elements Using the position Property
The CSS position in conjunction with the left, right, top and bottom property can be used to
align elements with respect to the document's viewport or containing parent element.

Example
Try this code »
.up {
position: absolute;
top: 0;
}
.down {
position: absolute;
bottom: 0;
}
To learn more about positioning elements, see the tutorial on CSS positioning.

Left and Right Alignment Using the float Property


The float CSS property can be used to align an element to the left or right of its containing
block in such a way that other content may flow along its side.

Hence, if an element is floated to the left, content will flow along its right side. Conversely, if
the element is floated to the right, content will flow along its left side.

Example
Try this code »
div {
width: 200px;
float: left;
}

Clearing Floats
One of the most confusing things about working with the float-based layouts is the collapsing
parent. The parent element doesn't stretch up automatically to accommodate the floated
elements. Though, this isn't always obvious if the parent doesn't contain any visually
noticeable background or borders, but it is important to be aware of and must dealt with to
prevent strange layout and cross-browser problem. See the illustration below:
You can see the <div> element doesn't stretch up automatically to accommodate the floated
images. This problem can be fixed by clearing the float after the floated elements in the
container but before the closing tag of the container element.

Fixing the Collapsed Parent


There are several ways to fix the CSS collapsing parent issue. The following section will
describe you these solutions along with the live examples.

Solution 1: Float the Container


The easiest way to fix this problem is to float the containing parent element.

Example
Try this code »
.container {
float: left;
background: #f2f2f2;
}
Warning: This fix will only work in a limited number of circumstances, since floating the
parent may produce unexpected results.

Solution 2: Using the Empty Div


This is an old fashioned way but is an easy solution and works across every browser.

Example
Try this code »
.clearfix {
clear: both;
}
/* html code snippet */
<div class="clearfix"> </div>
You could also do this by means of a <br> tag. But this method is not recommended since it
adds nonsemantic code to your markup.

Solution 3: Using the :after Pseudo-Element


The :after pseudo-element in conjunction with the content property has been used quite
extensively to resolve float-clearing issues.

Example
Try this code »
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
The class .clearfix is applied to any container that has floating children.

Warning: Internet Explorer up IE7 does not support the :after pseudo-element. However IE8
supported, but require a <!DOCTYPE> to be declared.

CSS Pseudo-classes
A CSS pseudo-class selector matches components based on an additional condition and not
necessarily defined by the document tree.

What is Pseudo-class
The CSS pseudo-classes allow you to style the dynamic states of an element such as hover,
active and focus state, as well as elements that are existing in the document tree but can't be
targeted via the use of other selectors without adding any IDs or classes to them, for example,
targeting the first or last child elements.

A pseudo-class starts with a colon (:). Its syntax can be given with:
selector:pseudo-class { property: value; }

The following section describes the most commonly used pseudo-classes.

Anchor Pseudo-classes
Using anchor pseudo-classes links can be displayed in different ways:
These pseudo-classes let you style unvisited links differently from visited ones. The most
common styling technique is to remove underlines from visited links.

Example
Try this code »
a:link {
color: blue;
}
a:visited {
text-decoration: none;
}
Some anchor pseudo-classes are dynamic — they're applied as a result of user interaction
with the document like on hover, or on focus etc.

Example
Try this code »
a:hover {
color: red;
}
a:active {
color: gray;
}
a:focus {
color: yellow;
}
These pseudo-classes change how the links are rendered in response to user actions.

 :hover applies when a user places cursor over the element, but does not select it.
 :active applies when the element is activated or clicked.
 :focus applies when the element has keyboard focus.

Note: To make these pseudo-classes work perfectly, you must define them in the exact order
— :link, :visited, :hover, :active, :focus.

The :first-child Pseudo-class


The :first-child pseudo-class matches an element that is the first child element of some
other element. The selector ol li:first-child in the example below select the first list item
of an ordered list and removes the top border form it.

Example
Try this code »
ol li:first-child {
border-top: none;
}
Note: To make :first-child to work in Internet Explorer 8 and earlier versions,
a <!DOCTYPE> must be declared at the top of document.

The :last-child Pseudo-class


The :last-child pseudo-class matches an element that is the last child element of some
other element. The selector ul li:last-child in the example below select the last list item
from an unordered list and removes the right border from it.

Example
Try this code »
ul li:last-child {
border-right: none;
}
Note: The CSS :last-child selector does not work in Internet Explorer 8 and earlier versions.
Supports in Internet Explorer 9 and above.

The :nth-child Pseudo-class


The CSS3 introduces a new :nth-child pseudo-class that allows you to target one or more
specific children of a given parent element. The basic syntax of this selector can be given
with :nth-child(N), where N is an argument, which can be a number, a keyword (even or odd),
or an expression of the form xn+y where x and y are integers (e.g. 1n, 2n, 2n+1, …).

Example
Try this code »
table tr:nth-child(2n) td {
background: #eee;
}
The style rules in the example above simply highlight the alternate table row, without adding
any IDs or classes to the <table> elements.

Tip: The CSS :nth-child(N) selector is very useful in the situations where you have to select
the elements that appears inside the document tree in a specific interval or pattern like at
even or odd places, etc.
The :lang Pseudo-class
The language pseudo-class :lang allows constructing selectors based on the language setting
for specific tags. The :lang pseudo-class in the example below defines the quotation marks
for <q> elements that are explicitly given a language value of no.

Example
Try this code »
q:lang(no) {
quotes: "~" "~";
}
/* HTML code snippet */
<p>Some text <q lang="no">A quote in a paragraph</q> Some text.</p>
Note: Internet Explorer up to version 7 does not support the :lang pseudo-class. IE8 supports
only if a <!DOCTYPE> is specified.

Pseudo-classes and CSS Classes


Pseudo-classes can be combined with CSS classes.

The link with class="red", in the example below will be displayed in red.

Example
Try this code »
a.red:link { /* style rule */
color: #ff0000;
}
<a class="red" href="#">Click me</a> /* HTML code snippet */

CSS Pseudo-elements
The CSS pseudo-elements is a ways to style elements of the document that weren't explicitly
defined by a position in the document tree.

What is Pseudo-element
The CSS pseudo-elements allow you to style the elements or parts of the elements without
adding any IDs or classes to them. It will be really helpful in the situations when you just want
to style the first letter of a paragraph to create the drop cap effect or you want to insert some
content before or after an element, etc. only through style sheet.

CSS3 introduced a new double-colon (::) syntax for pseudo-elements to distinguish between
them and pseudo-classes. The new syntax of the pseudo-element can be given with:
selector::pseudo-element { property: value; }

These are the following most commonly used pseudo-elements:

The ::first-line Pseudo-element


The ::first-line pseudo-element applies special style to the first line of a text.

The style rules in the following example formats the first line of text in a paragraph. The
length of first line depends on the size of the browser window or containing element.

Example
Try this code »
p::first-line {
color: #ff0000;
font-variant: small-caps;
}
Note: The CSS properties that can be applied to the ::first-line pseudo-element are: font
properties, background properties, color, word-spacing, letter-spacing, text-
decoration, vertical-align, text-transform, line-height.

The ::first-letter Pseudo-element


The ::first-letter pseudo-element is used to add a special style to the first letter of the first
line of a text. The style rules in the following example formats the first letter of the paragraph
of text and create the effect like drop cap.

Example
Try this code »
p::first-letter {
color: #ff0000;
font-size: xx-large;
}
Note: The CSS properties that can be applied to the ::first-letter pseudo-element are: font
properties, text-decoration, text-transform, letter-spacing, word-spacing, line-
height, float, vertical-align (only if 'float' is 'none'), color, margin and padding
properties, border properties, background properties.
The ::before and ::after Pseudo-element
The ::before and ::after pseudo-elements can be used to insert generated content either
before or after an element's content. The content CSS property is used in conjunction with
these pseudo-elements, to insert the generated content.

This is very useful for further decorating an element with rich content that should not be part
of the page's actual markup. You can insert regular strings of text or an embedded object
such as image and other resources using these pseudo-elements.

Example
Try this code »
h1::before {
content: url("images/marker-left.gif");
}
h1::after {
content: url("images/marker-right.gif");
}

Pseudo-elements and CSS Classes


Generally we need to style only a certain paragraph of text or other block-level elements with
these pseudo-elements. That's where declaring a class to the pseudo-element comes into
play. The pseudo-elements can be combined with the CSS classes to produce the effect
particularly for the elements having that class.

The style rules in the following example will display the first letter of all paragraphs with
the class="article", in green and size of xx-large.

Example
Try this code »
p.article::first-letter {
color: #00ff00;
font-size: xx-large;
}

CSS Media Types. Introduction to Media Types


One of the most important features of style sheets is that, you can specify separate style
sheets for different media types. This is one of the best ways to build printer friendly Web
pages — Just assign a different style sheet for the "print" media type.
Some CSS properties are only designed for certain media. For example, the page-break-
after property only applies to paged media. However there are several properties that may
be shared by different media types, but may require different values for that property.
The font-size property for example can be used for both screen and print media, but
possibly with different values. A document usually needs a larger font on a computer screen
as compared to the paper for better readability, also sans-serif fonts are considered easier to
read on the screen, while serif fonts are popular for printing. Therefore it is necessary to
specify that a style sheet, or a set of style rules, applies to certain media types.

Creating Media Dependent Style Sheets


Three methods are commonly used to specify the media dependencies for style sheets:

Method 1: Using the @media At-rules


The @media rule is used to define different style rules for different media types in a single style
sheet. It is usually followed by a comma-separated list of media types and the CSS
declarations block containing the styles rules for target media.

The style declaration in the example below tells the browser to display body content in 14
pixels Arial font on the screen, but in case of printing it will be in a 12 points Times font.
However the value of line-height property is set to 1.2 for both of them:

Example
Try this code »
@media screen{
body {
color: #32cd32;
font-family: Arial, sans-serif;
font-size: 14px;
}
}
@media print {
body {
color: #ff6347;
font-family: Times, serif;
font-size: 12pt;
}
}
@media screen, print {
body {
line-height: 1.2;
}
}
Note: Style rules outside of @media rules apply to all media types that the style sheet applies
to. At-rules inside @media are invalid in CSS2.1.

Method 2: Using the @import At-rules


The @import rule is another way of setting style information for a specific target media — Just
specify the comma-separated media types after the URL of the imported style sheets.

Example
Try this code »
@import url("css/screen.css") screen;
@import url("css/print.css") print;
body {
background: #f5f5f5;
line-height: 1.2;
}
The print media type in the @import statement instructs the browser to load an external style
sheet (print.css) and use its styles only for print media.

Note: All @import statements must occur at the beginning of a style sheet, before any
declarations. Any style rule specified in the style sheet itself override the conflicting style rules
in the imported style sheets.

Method 3: Using the <link> element


The media attribute on the <link> element is used to specify the target media for an external
style sheet within the HTML document.

Example
Try this code »
<link rel="stylesheet" media="all" href="css/common.css">
<link rel="stylesheet" media="screen" href="css/screen.css">
<link rel="stylesheet" media="print" href="css/print.css">
In this example the media attribute instructs the browser to load an external style sheet
"screen.css" and use its styles only for screen while "print.css" for printing purpose.

Tip: You can also specify multiple media types (each separated with comma
e.g. media="screen, print") as well as media quires to the <link> element.
Different Media Types
The following table lists the various media types that may used to target different types of
devices such as printers, handheld devices, computer screens etc.

Media Type Description

all Used for all media type devices.

aural Used for speech and sound synthesizers.

braille Used for braille tactile feedback devices.

embossed Used for paged braille printers.

handheld Used for small or handheld devices — usually small screen devices such as mobile phones or
PDAs.

print Used for printers.

projection Used for projected presentations, for example projectors.

screen Used primarily for color computer screens.

tty Used for media using a fixed-pitch character grid — such as teletypes, terminals, or portable
devices with limited display capabilities.

tv Used for television-type devices — low resolution, color, limited-scrollability screens, sound
available.

Warning: However there are several media types to choose from but most of the browser
only support all, screen and print media types.

CSS Sprites
CSS sprites technique is a way to reduce the number of HTTP requests made for image
resources, by combining images in a single file.
What is a Sprite
Sprites are two-dimensional images which are made up of combining small images into one
larger image at defined X and Y coordinates.

To display a single image from the combined image, you could use the CSS background-
position property, defining the exact position of the image to be displayed.

Advantage of Using CSS Image Sprite


A web page with many images, particularly many small images, such as icons, buttons, etc.
can take a long time to load and generates multiple server requests.

Using the image sprites instead of separate images will significantly reduce the number of
HTTP requests a browser makes to the server, which can be very effective for improving the
loading time of web pages and overall site performance.

Note: Reducing the number of HTTP requests has the major impact on reducing response
time that makes the web page more responsive for the user.

Checkout the following examples and you will see one visible difference; when you place the
mouse pointer over the browser icons in non-sprite version for the first time the hover image
will appear after some time, it happens because the hover image is loaded from the server on
mouse hover, since the normal and hover images are two different images.

Whereas in sprite version, since all images are combined in a single image the hover image is
displayed immediately on mouse hover that results in smooth hover effect.

 Firefox
 Chrome
 Explorer
 Safari
 Opera
 Firefox
 Chrome
 Explorer
 Safari
 Opera

Using CSS sprite technique demonstrated in the: [EXAMPLE - B]; we were able to reduce the
number of HTTP requests by 9 and the total file size of the image(s) by 38.2 KB as compared
to the [EXAMPLE - A];. That's a pretty huge improvement for such a small example. Imagine
what you could do on a complete website. The whole process of creating this example is
explained below.

Making the Image Sprite


We made this sprite image by combining 10 separate images in a single image ( mySprite.png).
You can create your own sprite using any image editing tool you like.
Tip: For the sake of simplicity, we have used all icons of same size, and place them closely to
each other for easy offset calculation.

Display an Icon from Image Sprite


Finally, utilizing CSS, we can display just the part of an image sprite we need.

First of all, we will create the class .sprite that will load our sprite image. This is to avoid
repetition, because all items share the same background-image.

Example
Try this code »
.sprite {
background: url("images/mySprite.png") no-repeat;
}
Now, we must define a class for each item we want to display. For example, to display Internet
Explorer icon form the image sprite the CSS code would be.

Example
Try this code »
.ie {
width: 50px; /* Icon width */
height: 50px; /* Icon height */
display: inline-block; /* Display icon as inline block */
background-position: 0 -200px; /* Icon background position in sprite
*/
}
Now the question arises, how did we get those pixel values for background-position? Let's find
out. The first value is the horizontal position, and second is the vertical position of background.
As the upper-left corner of Internet Explorer icon touches the left edge so its horizontal
distance from the starting point i.e. top-left corner of the image sprite is 0, and since it is
placed on the 5th position so its vertical distance from the starting point of image sprite is 4 X
50px = 200px, because height of each icon is 50px.

To show the Internet Explorer icon we have to move its upper-left corner to the starting point
i.e. top-left corner of image sprite (mySprite.png). Also, since this icon is placed at the vertical
distance of 200px, we will need to shift the whole background-image (mySprite.png) vertically
up by 200px, which requires us to apply the value as a negative number that is -200px,
because the negative value makes it go vertically up whereas a positive value would move it
down. However, it doesn't require a horizontal offset, since there are no pixels before the
upper-left corner of the Internet Explorer icon.
Tip: Just play around with the value of background-position property in the upcoming examples
and you will quickly learn how the offsets work.

Creating a Navigation Menu Using CSS Image Sprite


In the previous section we have learned, how to display an individual icon from an image
sprite. This is the easiest way to use image sprites, now we are going one step ahead by
building a navigation menu with rollover effect as demonstrated in [EXAMPLE - B].

Here we will use the same sprite image (mySprite.png) to create our navigation menu.

Foundation HTML for Navigation


We will start by creating our navigation menu with an HTML unordered list.

Example
Try this code »
<ul class="menu">
<li class="firefox"><a href="#">Firefox</a></li>
<li class="chrome"><a href="#">Chrome</a></li>
<li class="ie"><a href="#">Explorer</a></li>
<li class="opera"><a href="#">Opera</a></li>
<li class="safari"><a href="#">Safari</a></li>
</ul>

Applying the CSS on Navigation


The following sections will describes you how to convert the simple unordered list given in
example above to a spite image based navigation using the CSS.

Step 1: Resetting the List Structure


By default, HTML unordered lists are displayed with bullets. We'll need to remove the default
bullets by setting the list-style-type attribute to none.

Example
Try this code »
ul.menu {
list-style-type: none;
}
ul.menu li {
padding: 5px;
font-size: 16px;
font-family: "Trebuchet MS", Arial, sans-serif;
}

Step 2: Setting Common Properties for Each Links


In this step we will set all the common CSS properties that all links are going to share. Such
as, color, background-image, display, padding, etc.

Example
Try this code »
ul.menu li a {
height: 50px;
line-height: 50px;
display: inline-block;
padding-left: 60px; /* To sift text off the background-image */
color: #3E789F;
background: url("images/mySprite.png") no-repeat; /* As all link share
the same background-image */
}

Step 3: Setting Default State of Each Links


Now, we must define a class for each menu item, because every item in the image sprite has
different background-position. For example, Firefox icon is placed at the starting point i.e. top-
left corner of the image sprite, so there is no need to shift the background-image. Hence the
vertical and horizontal position of the background in this case would be 0. Similarly, you can
define background-position for other icons within the image sprite.

Example
Try this code »
ul.menu li.firefox a {
background-position: 0 0;
}
ul.menu li.chrome a {
background-position: 0 -100px;
}
ul.menu li.ie a {
background-position: 0 -200px;
}
ul.menu li.safari a {
background-position: 0 -300px;
}
ul.menu li.opera a {
background-position: 0 -400px;
}
Step 4: Adding Hover States of Links
Adding hover states owns the same principle as adding the above links. Just move their
upper-left corner to the starting point (i.e. top-left corner) of the image sprite as we have
done above. You can simply calculate the background-position using the following formula:
Vertical position of hover state = Vertical position of normal state - 50px

As rollover images are just below the default state and height of each icon is equal to 50px.
The hover state of icons also doesn't require a horizontal offset, since there are no pixels
before the upper-left corner of them.

Example
Try this code »
ul.menu li.firefox a:hover {
background-position: 0 -50px;
}
ul.menu li.chrome a:hover {
background-position: 0 -150px;
}
ul.menu li.ie a:hover {
background-position: 0 -250px;
}
ul.menu li.safari a:hover {
background-position: 0 -350px;
}
ul.menu li.opera a:hover {
background-position: 0 -450px;
}
Done! Here is our final HTML and CSS code after combining the whole process:

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Sprite Navigation Menu</title>
<style>
ul.menu {
list-style-type: none;
}
ul.menu li {
padding: 5px;
font-size: 16px;
font-family: "Trebuchet MS", Arial, sans-serif;
}
CSS Opacity. Cross Browser Opacity
Opacity is now a part of the CSS3 specifications, but it was present for a long time. However,
older browsers have different ways of controlling the opacity or transparency.

CSS Opacity in Firefox, Safari, Chrome, Opera and IE9


Here is the most up to date syntax for CSS opacity in all current browsers.

Example
Try this code »
p {
opacity: 0.7;
}
The above style rule will make the paragraph element 70% opaque (or 30% transparent).

The opacity property takes a value a value from 0.0 to 1.0. A setting of opacity: 1; would make
the element completely opaque (i.e. 0% transparent), whereas opacity: 0; would make the
element completely transparent (i.e. 100% transparent).

CSS Opacity in Internet Explorer 8 and lower


Internet Explorer 8 and earlier version supports a Microsoft-only property "alpha filter" to
control the transparency of an element.

Example
Try this code »
p {
filter: alpha(opacity=50);
zoom: 1; /* Fix for IE7 */
}
Note: Alpha filters in IE accept values from 0 to 100. The value 0 makes the element completely
transparent (i.e. 100% transparent), whereas the value 100 makes the element completely
opaque (i.e. 0% transparent).

CSS Opacity for All Browser


Combining the both steps above you will get the opacity for all browsers.

Example
Try this code »
p {
opacity: 0.5; /* Opacity for Modern Browsers */
filter: alpha(opacity=50); /* Opacity for IE8 and lower */
zoom: 1; /* Fix for IE7 */
}
Warning: Including alpha filter to control transparency in Internet Explorer 8 and lower
versions creates invalid code in your style sheet since this is a Microsoft-only property, not a
standard CSS property.

CSS Image Opacity


You can also make transparent images using CSS Opacity. The three images in the illustration
below are all from the same source image. The only differences between them are the level of
their opacity.

opacity:1 opacity:0.5 opacity:0.25

Change Image Opacity on Mouse Over


The following example demonstrates a common use of CSS image opacity, where the opacity
of images changes when the user moves the mouse pointer over an image.

— Move your mouse pointer over the images to see the effect.
Text in Transparent Box
When using opacity on an element not only the background of the element that will have
transparency, but all of its child elements become transparent as well. It is making the text
inside the transparent element hard to read if the value of opacity becomes higher.

OPACITY OPACITY OPACITY OPACITY


To prevent this either you can use transparent PNG images, or put the text block outside of
the transparent box and push it visually inside using the negative margin or CSS positioning.

Example
Try this code »
div {
float: left;
opacity: 0.7;
border: 1px solid #949781;
}
p {
float: left;
position: relative;
margin-left: -400px;
}

CSS Transparency Using RGBA


In addition to RGB CSS3 has introduced a new way RGBA to specify a color that includes alpha
transparency as part of the color value. RGBA stands for Red Blue Green Alpha.

The RGBA declaration is a very easy way to set transparency for a color.

Example
Try this code »
div {
background: rgba(200, 54, 54, 0.5);
}
p {
color: rgba(200, 54, 54, 0.25);
}
The first three numbers representing the color in RGB values i.e. red (0-255), green (0-255),
blue (0-255) and the fourth representing alpha transparency value between 0 to 1 (0 makes
the color fully transparent , whereas the value of 1 makes it fully opaque).
One important characteristic to note about the RGBA transparency is that — the ability to
control the opacity of individual color. With RGBA, we can make the text color of an element
transparent and leave background intact.

RGBA RGBA RGBA RGBA


— Or leave the text color alone and change only the transparency of background.

RGBA RGBA RGBA RGBA


You can see how easily you can control the opacity of individual colors rather than the entire
element using RGBA. However it is always recommended to define a fallback color for the
browsers that do not support the RGBA colors.

Note: The RGBA transparency doesn't affect the child elements the way the opacity property
does. The alpha value of RGBA affects the transparency of individual color rather than the
entire element.

Declaring a Fallback Color


All browsers do not support RGBA colors. However, you can provide an alternative such as
solid colors or transparent PNG images for the browsers that don't support it.

Example
Try this code »
p {
/* Fallback for web browsers that doesn't support RGBA */
background: rgb(0, 0, 0);
/* RGBa with 0.5 opacity */
background: rgba(0, 0, 0, 0.5);
}
Warning: Internet Explorer 8 and earlier versions do not support the RGBA colors. They use
the gradient filter to achieve the effect of RGBA, which is deprecated.

CSS Attribute Selectors


An attribute selector selects the HTML elements that has a specific attribute or attribute with a
specified value.

Understanding the Attribute Selectors


The CSS attribute selectors provides an easy and powerful way to apply the styles on HTML
elements based on the presence of a particular attribute or attribute value.
You can create an attribute selector by putting the attribute—optionally with a value—in a
pair of square brackets. You can also place an element type selector before it.

The following sections describe the most common attribute selectors.

CSS [attribute] Selector


This is the simplest form of an attribute selector that applies the style rules to an element if a
given attribute exists. For example, we can style all the elements that have a title attribute by
using the following style rules:

Example
Try this code »
[title] {
color: blue;
}
The selector [title] in the above example matches all elements that has a title attribute.

You can also restrict this selection to a particular HTML element by placing the attribute
selector after an element type selector, like this:

Example
Try this code »
abbr[title] {
color: red;
}
The selector abbr[title] matches only <abbr> elements that has a title attribute, so it matches
the abbreviation, but not the anchor elements having title attribute.

CSS [attribute="value"] Selector


You can use the = operator to make an attribute selector matches any element whose
attribute value is exactly equal to the given value:

Example
Try this code »
input[type="submit"] {
border: 1px solid green;
}
The selector in the above example matches all <input> element that has a type attribute with a
value equal to submit.
CSS [attribute~="value"] Selector
You can use the ~= operator to make an attribute selector matches any element whose
attribute value is a list of space-separated values (like class="alert warning") , one of which is
exactly equal to the specified value:

Example
Try this code »
[class~="warning"] {
color: #fff;
background: red;
}
This selector matches any HTML element with a class attribute that contains space-separated
values, one of which is warning. For example, it matches the elements having the class
values warning, alert warning etc.

CSS [attribute|="value"] Selector


You can use the |= operator to make an attribute selector matches any element whose
attribute has a hyphen-separated list of values beginning with the specified value:

Example
Try this code »
[lang|=en] {
color: #fff;
background: blue;
}
The selector in the above example matches all elements that has an lang attribute containing a
value start with en, whether or not that value is followed by a hyphen and more characters. In
other words, it matches the elements with lang attribute that has the values en, en-US, en-GB, and
so on but not US-en, GB-en.

CSS [attribute^="value"] Selector


You can use the ^= operator to make an attribute selector matches any element whose
attribute value starts with a specified value. It does not have to be a whole word.

Example
Try this code »
a[href^="http://"] {
background: url("external.png") 100% 50% no-repeat;
padding-right: 15px;
}
The selector in the example above will target all external links and add a small icon indicating
that they will open in a new tab or window.

CSS [attribute$="value"] Selector


Similarly, you can use the $= operator to select all elements whose attribute value ends with a
specified value. It does not have to be a whole word.

Example
Try this code »
a[href$=".pdf"] {
background: url("pdf.png") 0 50% no-repeat;
padding-left: 20px;
}
The selector in the example above select all <a> elements that links to a PDF document and
add a small PDF icon to provide hints to the user about the link.

CSS [attribute*="value"] Selector


You can use the *= operator to make an attribute selector matches all elements whose
attribute value contains a specified value.

Example
Try this code »
[class*="warning"] {
color: #fff;
background: red;
}
This selector in the example above matches all HTML elements with a class attribute that
values contains warning. For example, it matches the elements having class values warning, alert
warning, alert-warning or alert_warning etc.

Styling Forms with Attribute Selectors


The attribute selectors are particularly useful for styling forms without class or id:

Example
Try this code »
input[type="text"], input[type="password"] {
width: 150px;
display: block;
margin-bottom: 10px;
background: yellow;
}
input[type="submit"] {
padding: 2px 10px;
border: 1px solid #804040;
background: #ff8040;
}

CSS Validation
CSS validation is the process of checking the code against the formal guidelines and
standards set by the Wide Web Consortium (W3C) for CSS document.

Why Validate Your CSS Code


As a beginner, it is very common that you will make mistake in writing your CSS code.
Incorrect or non-standard code may cause unexpected results in how your page displayed or
functions in a web browser. The World Wide Web Consortium (W3C) has created a great
tool https://jigsaw.w3.org/css-validator/ to automatically check your style sheets, and point out
any problems/errors your code might have, such as invalid CSS property missing closing
bracket or missing semicolon (;) etc. It is absolutely free.

Validating a Website
Website validation is the process to ensure that the pages of a website conform to the formal
guidelines and standards set by the World Wide Web Consortium (W3C). There are several
specific reasons for validating a website, some of them are:

 It helps to create Web pages that are cross-browser, cross-platform compatible. It also
likely to be compatible with the future version of Web browsers and Web standards.
 Standards compliant web pages increase the search engines spider visibility and your
pages will more likely be appear in search results.
 It will reduce unexpected errors and make your web pages more accessible to the visitor of
your website.

Note: Validation is important. It will ensure that your web pages are interpreted in the same
way (the way you want it) by the various web browsers, search engines etc. as well as users
and visitors of your Web site.
Follow the link given below to validate your CSS document.
W3.org's CSS Validator

CSS3 Border
With CSS3, you can apply images to an element's borders.

Using CSS3 Borders


The CSS3 provides two new properties for styling the borders of an element in a more elegant
way — the border-image property for adding the images to borders, and the border-
radius property for making the rounded corners without using any images.

The following section will describe you these new border properties of CSS3, for other border
related properties please check out the CSS border tutorial.

Creating CSS3 Rounded Corners


The border-radius property can be used to create rounded corners. This property typically
defines the shape of the corner of the outer border edge. Prior to CSS3, sliced images are
used for creating the rounded corners that was rather bothersome.

Example
Try this code »
.box {
width: 300px;
height: 150px;
background: #ffb6c1;
border: 2px solid #f08080;
border-radius: 20px;
}

Adding CSS3 Border Images


The border-image property allows you to specify an image to act as an element's border.
The design of the border is created from the sides and corners of the image specified
in border-image source URL. The border image may be sliced, repeated, scaled and stretched in
various ways to fit the size of the border image area.
Example
Try this code »
.box {
width: 300px;
height: 150px;
border: 15px solid transparent;
-webkit-border-image: url("border.png") 30 30 round; /* Safari 3.1-5
*/
-o-border-image: url("border.png") 30 30 round; /* Opera 11-12.1 */
border-image: url("border.png") 30 30 round;
}
Tip: The round option is a variation of the repeat option that distributes the image tiles in
such a way that the ends are nicely connected.

CSS3 Color
CSS3 provides several new ways to define a color values.

Defining Colors in CSS3


In the previous section you've learnt how to define colors using the color keywords and RGB
notations. In addition to that CSS3 adds some new functional notations for setting color
values for the elements which are rgba(), hsl() and hsla().

In the following section we'll discuss about these color model one by one.

RGBA Color Values


Colors can be defined in the RGBA model (red-green-blue-alpha) using the rgba() functional
notation. RGBA color model are an extension of RGB color model with an alpha channel —
which specifies the opacity of a color.

The alpha parameter accepts a value from 0.0 (fully transparent) to 1.0 (fully opaque).

Example
Try this code »
h1 {
color: rgba(0,0,255,0.5);
}
p {
background-color: rgba(0%,0%,100%,0.3);
}

HSL Color Values


Colors also can be defined the HSL model (hue-saturation-lightness) using
the hsl() functional notation. Hue is represented as an angle (from 0 to 360) of the color
wheel or circle (i.e. the rainbow represented in a circle). This angle is given as a unit less
number because the angle is so typically measured in degrees that the unit is implicit in CSS.

Saturation and lightness are represented as percentages. 100% saturation means full color,
and 0% is a shade of gray. Whereas, 100% lightness is white, 0% lightness is black,
and 50% lightness is normal. Check out the example below:

Example
Try this code »
h1 {
color: hsl(360,70%,60%);
}
p {
background-color: hsl(480,50%,80%);
}
Tip: By the definition red=0=360, and the other colors are spread around the circle,
so green=120, blue=240, etc. As an angle, it implicitly wraps around such that -
120=240, 480=120, and so on.

HSLA Color Values


Colors can be defined in the HSLA model (hue-saturation-lightness-alpha) using
the hsla() functional notation. HSLA color model are an extension of HSL color model with
an alpha channel — which specifies the opacity of a color.

The alpha parameter accepts a value from 0.0 (fully transparent) to 1.0 (fully opaque).

Example
Try this code »
h1 {
color: hsla(360,80%,50%,0.5);
}
p {
background-color: hsla(480,60%,30%,0.3);
}
CSS3 Background
With CSS3, you can apply multiple backgrounds to elements.

Using CSS3 Backgrounds


The CSS3 provides several new properties to manipulate the background of an element like
background clipping, multiple backgrounds, and the option to adjust the background size.

The following section will describe you all the new background features of CSS3, for other
background related properties please check out the CSS background tutorial.

CSS3 background-size Property


The background-size property can be used to specify the size of the background images. Prior
to CSS3, the size of the background images was determined by the actual size of the images.
The background image size can be specified using the pixels or percentage values as well as
the keywords auto, contain, and cover. Negative values are not allowed.

Example
Try this code »
.box {
width: 250px;
height: 150px;
background: url("images/sky.jpg") no-repeat;
background-size: contain;
border: 6px solid #333;
}
Tip: The background-size property is typically used to create full size background images that
scale according to the size of viewport or witdh of the browser.

CSS3 background-clip Property


The background-clip property can be used to specify whether an element's background extends
into the border or not. The background-clip property can take the three values: border-
box, padding-box, content-box.
Example
Try this code »
.box {
width: 250px;
height: 150px;
padding: 10px;
border: 6px dashed #333;
background: orange;
background-clip: content-box;
}
See the tutorial on CSS box model to learn more about element's boxes.

CSS3 background-origin Property


The background-origin property can be used to specify the positioning area of the background
images. It can take the same values as background-clip property: border-box, padding-box, content-
box.

Example
Try this code »
.box {
width: 250px;
height: 150px;
padding: 10px;
border: 6px dashed #333;
background: url("images/sky.jpg") no-repeat;
background-size: contain;
background-origin: content-box;
}
Note: The background-origin property is ignored if the value of background-attachment property is
specified as 'fixed'.

CSS3 Multiple Backgrounds


CSS3 gives you the ability to add multiple backgrounds to a single element. The backgrounds
are layered on the top of one another. The number of layers is determined by the number of
comma-separated values in the background-image or background shorthand property.

Example
Try this code »
.box {
width: 100%;
height: 500px;
background: url("images/birds.png") no-repeat center,
url("images/clouds.png") no-repeat center, lightblue;
}
The first value in the comma-separated list of backgrounds i.e. the background-image 'birds.png'
will appear on the top and the last value i.e. the 'lightblue' color will appear at the bottom.
Only the last background can include a background-color.

CSS3 Gradients
The CSS3 gradient feature allows you to create a gradient from one color to another without
using any images.

Using CSS3 Gradients


The CSS3 gradient feature provides a flexible solution to generate smooth transitions between
two or more colors. Earlier, to achieve such effect we had to use the images. Using CSS3
gradients you can reduce the download time and saves the bandwidth usages. The elements
with gradients can be scaled up or down to any extent without losing the quality, also the
output will render much faster because it is generated by the browser.

Gradients are available in two styles: linear and radial.

Creating CSS3 Linear Gradients


To create a linear gradient you must define at least two color stops. However to create more
complex gradient effects you can define more color stops. Color stops are the colors you want
to render smooth transitions among. You can also set a starting point and a direction (or an
angle) along which the gradient effect is applied. The basic syntax of creating the linear
gradients using the keywords can be given with:
linear-gradient(direction, color-stop1, color-stop2, ...)

Linear Gradient - Top to Bottom


The following example will create a linear gradient from top to bottom. This is default.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(red, yellow);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(red, yellow);
/* Standard syntax */
background: linear-gradient(red, yellow);
}

Linear Gradient - Left to Right


The following example will create a linear gradient from left to right.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(left, red, yellow);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(left, red, yellow);
/* Standard syntax */
background: linear-gradient(to right, red, yellow);
}

Linear Gradient - Diagonal


You can also create a gradient along the diagonal direction. The following example will create
a linear gradient from the bottom left corner to the top right corner of the element's box.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(bottom left, red, yellow);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(bottom left, red, yellow);
/* Standard syntax */
background: linear-gradient(to top right, red, yellow);
}
Setting Direction of Linear Gradients Using Angles
If you want more control over the direction of the gradient, you can set the angle, instead of
the predefined keywords. The angle 0deg creates a bottom to top gradient, and positive
angles represent clockwise rotation, that means the angle 90deg creates a left to right
gradient. The basic syntax of creating the linear gradients using angle can be given with:
linear-gradient(angle, color-stop1, color-stop2, ...)

The following example will create a linear gradient from left to right using angle.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(0deg, red, yellow);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(0deg, red, yellow);
/* Standard syntax */
background: linear-gradient(90deg, red, yellow);
}

Creating Linear Gradients Using Multiple Color Stops


You can also create gradients for more than two colors. The following example will show you
how to create a linear gradient using multiple color stops. All colors are evenly spaced.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(red, yellow, lime);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(red, yellow, lime);
/* Standard syntax */
background: linear-gradient(red, yellow, lime);
}
Setting the Location Color Stops
Color stops are points along the gradient line that will have a specific color at that location.
The location of a color stop can be specified either as a percentage, or as an absolute length.
You may specify as many color stops as you like to achieve the desired effect.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(red, yellow 30%, lime 60%);
/* For Internet Explorer 10 */
background: -ms-linear-gradient(red, yellow 30%, lime 60%);
/* Standard syntax */
background: linear-gradient(red, yellow 30%, lime 60%);
}
Note: While setting the color-stops location as a percentage, 0% represents the starting point,
while 100% represents the ending point. However, you can use values outside of that range i.e.
before 0% or after 100% to get the effect you want.

Repeating the Linear Gradients


You can repeat linear gradients using the repeating-linear-gradient() function.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: white;
/* For Safari 5.1 to 6.0 */
background: -webkit-repeating-linear-gradient(black, white 10%, lime
20%);
/* For Internet Explorer 10 */
background: -ms-repeating-linear-gradient(black, white 10%, lime 20%);
/* Standard syntax */
background: repeating-linear-gradient(black, white 10%, lime 20%);
}
Creating CSS3 Radial Gradients
In a radial gradient color emerge from a single point and smoothly spread outward in a
circular or elliptical shape rather than fading from one color to another in a single direction as
with linear gradients. The basic syntax of creating a radial gradient can be given with:
radial-gradient(shape size at position, color-stop1, color-stop2, ...);

The arguments of the radial-gradient() function has the following meaning:

 position — Specifies the starting point of the gradient, which can be specified in units (px,
em, or percentages) or keyword (left, bottom, etc).
 shape — Specifies the shape of the gradient's ending shape. It can be circle or ellipse.
 size — Specifies the size of the gradient's ending shape. The default is farthest-side.

The following example will show you create a radial gradient with evenly spaced color stops.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-radial-gradient(red, yellow, lime);
/* For Internet Explorer 10 */
background: -ms-radial-gradient(red, yellow, lime);
/* Standard syntax */
background: radial-gradient(red, yellow, lime);
}

Setting the Shape of Radial Gradients


The shape argument of the radial-gradient() function is used to define the ending shape of
the radial gradient. It can take the value circle or ellipse. Here's is an example:

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-radial-gradient(circle, red, yellow, lime);
/* For Internet Explorer 10 */
background: -ms-radial-gradient(circle, red, yellow, lime);
/* Standard syntax */
background: radial-gradient(circle, red, yellow, lime);
}
Note: If the shape argument is omitted or not specified, the ending shape defaults to a circle
if the size is a single length, otherwise an ellipse.

Setting the Size of Radial Gradients


The size argument of the radial-gradient() function is used to define the size of the
gradient's ending shape. Size can be set using units or the keywords: closest-
side, farthest-side, closest-corner, farthest-corner.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: red;
/* For Safari 5.1 to 6.0 */
background: -webkit-radial-gradient(left bottom, circle farthest-side,
red, yellow, lime);
/* For Internet Explorer 10 */
background: -ms-radial-gradient(left bottom, circle farthest-side,
red, yellow, lime);
/* Standard syntax */
background: radial-gradient(circle farthest-side at left bottom, red,
yellow, lime);
}

Repeating the Radial Gradients


You can also repeat radial gradients using the repeating-radial-gradient() function.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: white;
/* For Safari 5.1 to 6.0 */
background: -webkit-repeating-radial-gradient(black, white 10%, lime
20%);
/* For Internet Explorer 10 */
background: -ms-repeating-radial-gradient(black, white 10%, lime 20%);
/* Standard syntax */
background: repeating-radial-gradient(black, white 10%, lime 20%);
}
CSS3 Transparency and Gradients
CSS3 gradients also support transparency. You can use this to create fading effects on
background images when stacking multiple backgrounds.

Example
Try this code »
.gradient {
/* Fallback for browsers that don't support gradients */
background: url("images/sky.jpg");
/* For Safari 5.1 to 6.0 */
background: -webkit-linear-gradient(left, rgba(255,255,255,0),
rgba(255,255,255,1)), url("images/sky.jpg");
/* For Internet Explorer 10 */
background: -ms-linear-gradient(left, rgba(255,255,255,0),
rgba(255,255,255,1)), url("images/sky.jpg");
/* Standard syntax */
background: linear-gradient(to right, rgba(255,255,255,0),
rgba(255,255,255,1)), url("images/sky.jpg");
}

CSS3 Text Overflow


CSS3 new text properties provide more control over the text rendering.

Handling Text Overflow in CSS3


CSS3 introduced several new property properties for modifing the text contents, however
some of these properties are existed from a long time. These properties give you precise
control over the rendering of text on the web browser.

Hiding Overflow Text


Text can overflow, when it is prevented from wrapping, for example, if the value of white-
space property is set to nowrap for the containing element or a single word is too long to fit like
a long email address. In such situation you can use the CSS3 text-overflow property to
determine how the overflowed text content will be displayed. You can either display or clip
the overflowed text or clip and display an ellipsis or a custom string in palace of the clipped
text to indicate the user.

Values Accepted by the word-break property are: clip and ellipsis and string.
Example
Try this code »
p {
width: 400px;
overflow: hidden;
white-space: nowrap;
background: #cdcdcd;
}
p.clipped {
text-overflow: clip; /* clipped the overflowed text */
}
p.ellipses {
text-overflow: ellipsis; /* display '…' to represent clipped text */
}
Warning: The string value for the text-overflow property is not supported in most of the web
browsers, you should better avoid this.

Breaking Overflow Text


You can also break a long word and force it to wrap onto a new line that overflows the
boundaries of containing element using the CSS3 word-wrap property.

Values Accepted by the word-wrap property are: normal and break-word.

Example
Try this code »
p {
width: 200px;
background: #ffc4ff;
word-wrap: break-word;
}
Tip: Please check out the individual property reference for all the possible values and the
Browser support for these CSS properties.

Specify Word Breaking Rules


You can also specify the line breaking rules for the text (i.e. how to break lines within words)
yourself using the CSS3 word-break property.

Values Accepted by the word-break property are: normal, break-all and keep-all.

Example
Try this code »
p {
width: 150px;
padding: 10px;
}
p.break {
background: #bedb8b;
word-break: break-all;
}
p.keep {
background: #f09bbb;
word-break: keep-all;

CSS3 Drop Shadows


With CSS3, you can apply drop shadow to an element.

Using CSS3 Drop Shadows


The CSS3 gives you the ability to add drop shadow effects to the elements like you do in
Photoshop without using any images. Prior to CSS3, sliced images are used for creating the
shadows around the elements that was quite annoying.

The following section will describe you how to apply the shadow on text and elements.

CSS3 box-shadow Property


The box-shadow property can be used to add shadow to the element's boxes. You can even
apply more than one shadow effects using a comma-separated list of shadows. The basic
syntax of creating a box shadow can be given with:
box-shadow: offset-x offset-y blur-radius color;

The components of the box-shadow property have the following meaning:

 offset-x — Sets the horizontal offset of the shadow.


 offset-y — Sets the vertical offset of the shadow.
 blur-radius — Sets the blur radius. The larger the value, the bigger the blur and more the
shadow's edge will be blurred. Negative values are not allowed.
 color — Sets the color of the shadow. If the color value is omitted or not specified, it takes
the value of the color property.

See the CSS3 box-shadow property to learn more about the other possible values.
Example
Try this code »
.box{
width: 200px;
height: 150px;
background: #ccc;
box-shadow: 5px 5px 10px #999;
}
Note: When adding the box-shadow, if the value for the blur-radius component is not
specified, or set to zero (0), the edges of the shadow will be sharp.

Similarly, you can add the multiple box shadow using a comma-separated list:

Example
Try this code »
.box{
width: 200px;
height: 150px;
background: #000;
box-shadow: 5px 5px 10px red, 10px 10px 20px yellow;
}

CSS3 text-shadow Property


You can use the text-shadow property to apply the shadow effects on text. You can also apply
multiple shadows to text using the same notation as box-shadow.

Example
Try this code »
h1 {
text-shadow: 5px 5px 10px #666;
}
h2 {
text-shadow: 5px 5px 10px red, 10px 10px 20px yellow;
}

CSS3 2D Transforms
The CSS3 2D transform feature allows elements to be transformed in 2D space.
2D Transformation of Elements
With CSS3 2D transform feature you can perform basic transform manipulations such as
move, rotate, scale and skew on elements in a two-dimensional space. A transformed element
doesn't affect the surrounding elements, but can overlap them, just like the absolutely
positioned elements. However, the transformed element still takes space in the layout at its
default (un-transformed) location.

Using CSS Transform and Transform Functions


The CSS3 transform property uses the transform functions to manipulate the coordinate
system used by an element in order to apply the transformation effect.

The following section describes these transform functions:

The translate() Function


Moves the element from its current position to a new position along the X and Y axes. This
can be written as translate(tx, ty). If ty isn't specified, its value is assumed to be zero.

Example
Try this code »
img {
-webkit-transform: translate(200px, 50px); /* Chrome, Safari, Opera
*/
-moz-transform: translate(200px, 50px); /* Firefox */
-ms-transform: translate(200px, 50px); /* IE 9 */
transform: translate(200px, 50px); /* Standard syntax */
}
The function translate(200px, 50px) moves the image 200 pixels horizontally along the
positive x-axis, and 50 pixels vertically along the positive y-axis.
The rotate() Function
The rotate() function rotates the element around its origin (as specified by the transform-
origin property) by the specified angle. This can be written as rotate(a).

Example
Try this code »
img {
-webkit-transform: rotate(30deg); /* Chrome, Safari, Opera */
-moz-transform: rotate(30deg); /* Firefox */
-ms-transform: rotate(30deg); /* IE 9 */
transform: rotate(30deg); /* Standard syntax */
}
The function rotate(30deg) rotates the image in clockwise direction about its origin by the
angle 30 degrees. You can use negative values to rotate the element counter-clockwise.

The scale() Function


The scale() function increases or decreases the size of the element. It can be written
as scale(sx, sy). If sy isn't specified, it is assumed to be equal to sx.

Example
Try this code »
img {
-webkit-transform: scale(1.5); /* Chrome, Safari, Opera */
-moz-transform: scale(1.5); /* Firefox */
-ms-transform: scale(1.5); /* IE 9 */
transform: scale(1.5); /* Modern Browsers */
}
The function scale(1.5) proportionally scale the width and height of the image 1.5 times to
its original size. The function scale(1) or scale(1, 1) has no effect on the element.

The skew() Function


The skew() function skews the element along the X and Y axes by the specified angles. It can
be written as skew(ax, ay). If ay isn't specified, its value is assumed to be zero.

Example
Try this code »
img {
-webkit-transform: skew(-40deg, 15deg); /* Chrome, Safari, Opera */
-moz-transform: skew(-40deg, 15deg); /* Firefox */
-ms-transform: skew(-40deg, 15deg); /* IE 9 */
transform: skew(-40deg, 15deg); /* Modern Browsers */
}
The function skew(-40deg, 15deg) skews the element -40 degree horizontally along the
x-axis, and 15 degree vertically along the y-axis.
The matrix() Function
The matrix() function can perform all of the 2D transformations such as translate, rotate,
scale, and skew at once. It takes six parameters in the form of a matrix which can be written
as matrix(a, b, c, d, e, f). The following section will show you how each of the 2D
transformation functions can be represented using the matrix().

 translate(tx, ty) = matrix(1, 0, 0, 1, tx, ty); — where tx and ty are the


horizontal and vertical translation values.
 rotate(a) = matrix(cos(a), sin(a), -sin(a), cos(a), 0, 0); — where a is the value
in deg. You can swap the sin(a) and -sin(a) values to reverse the rotation. The maximum
rotation you could perform is 360 degrees.
 scale(sx, sy) = matrix(sx, 0, 0, sy, 0 ,0); — where sx and sy are the horizontal
and vertical scaling values.
 skew(ax, ay) = matrix(1, tan(ay), tan(ay), 1, 0 ,0); — where ax and ay are the
horizontal and vertical values in deg.

Here is an example of performing the 2D transformation using the matrix() function.

Example
Try this code »
img {
-webkit-transform: matrix(0, -1, 1, 0, 200px, 50px); /* Chrome,
Safari, Opera */
-moz-transform: matrix(0, -1, 1, 0, 200px, 50px); /* Firefox */
-ms-transform: matrix(0, -1, 1, 0, 200px, 50px); /* IE 9 */
transform: matrix(0, -1, 1, 0, 200px, 50px); /* Standard
syntax */
}
However, when performing more than one transformation at once, it is more convenient to
use the individual transformation function and list them in order, like this:

Example
Try this code »
img {
-webkit-transform: translate(200px, 50px) rotate(180deg) scale(1.5)
skew(0, 30deg); /* Chrome, Safari, Opera */
-moz-transform: translate(200px, 50px) rotate(180deg) scale(1.5)
skew(0, 30deg); /* Firefox */
-ms-transform: translate(200px, 50px) rotate(180deg) scale(1.5)
skew(0, 30deg); /* IE 9 */
transform: translate(200px, 50px) rotate(180deg) scale(1.5)
skew(0, 30deg); /* Standard syntax */
}

2D Transform Functions
The following table provides a brief overview of all the 2D transformation functions.

Function Description

translate(tx,ty) Moves the element by the given amount along the X and Y-axis.

translateX(tx) Moves the the element by the given amount along the X-axis.

translateY(ty) Moves the the element by the given amount along the Y-axis.

rotate(a) Rotates the element by the specified angle around the origin of the element, as
defined by the transform-origin property.

scale(sx,sy) Scale the width and height of the element up or down by the given amount. The
function scale(1,1) has no effect.

scaleX(sx) Scale the width of the element up or down by the given amount.

scaleY(sy) Scale the height of the element up or down by the given amount.

skew(ax,ay) Skews the element by the given angle along the X and Y-axis.

skewX(ax) Skews the element by the given angle along the X-axis.

skewY(ay) Skews the element by the given angle along the Y-axis.

matrix(n,n,n,n,n,n) Specifies a 2D transformation in the form of a transformation matrix comprised of


the six values.

CSS3 3D Transforms
The CSS3 3D transform feature allows elements to be transformed in 3D space.
3D Transformation of Elements
With CSS3 3D transform feature you can perform basic transform manipulations such as
move, rotate, scale and skew on elements in a three-dimensional space.

A transformed element doesn't affect the surrounding elements, but can overlap them, just
like the absolutely positioned elements. However, the transformed element still takes space in
the layout at its default (un-transformed) location.

Using CSS Transform and Transform Functions


The CSS3 transform property uses the transform functions to manipulate the coordinate
system used by an element in order to apply the transformation effect.

The following section describes the 3D transform functions:

The translate3d() Function


Moves the element from its current position to a new position along the X, Y and Z-axis. This
can be written as translate(tx, ty, tz). Percentage values are not allowed for third
translation-value parameter (i.e. tz).

Example
Try this code »
.container {
width: 125px;
height: 125px;
perspective: 500px;
border: 4px solid #e5a043;
background: #fff2dd;
}
.transformed {
-webkit-transform: translate3d(25px, 25px, 50px); /* Chrome, Safari,
Opera */
transform: translate3d(25px, 25px, 50px); /* Standard syntax */
}
The function translate3d(25px, 25px, 50px) moves the image 25 pixels along the positive
X and Y-axis, and the 50 pixels along the positive Z-axis.
The 3D transform however uses the three-dimensional coordinate system, but movement
along the Z-direction is not always noticeable because the elements exist on a two-
dimensional plane (a flat surface) and have no depth. The perspective and perspective-
origin CSS properties can be used to add a feeling of depth to a scene by making the
elements higher on the Z-axis i.e. closer to the viewer appear larger, and those further away to
the viewer appear smaller.

Note: If you apply 3D transformation to an element without setting the perspective the
resulting effect will not appear as three-dimensional.

The rotate3d() Function


The rotate3d() function rotates the element in 3D space by the specified angle around the
[x,y,z] direction vector. This can be written as rotate(vx, vy, vz, angle).

Example
Try this code »
.container{
width: 125px;
height: 125px;
perspective: 300px;
border: 4px solid #a2b058;
background: #f0f5d8;
}
.transformed {
-webkit-transform: rotate3d(0, 1, 0, 60deg); /* Chrome, Safari, Opera
*/
transform: rotate3d(0, 1, 0, 60deg); /* Standard syntax */
}
The function rotate3d(0, 1, 0, 60deg) rotates the image along the Y-axis by the angle 60
degrees. You can use negative values to rotate the element in opposite direction.
The scale3d() Function
The scale3d() function changes the size of an element. It can be written as scale(sx, sy,
sz). The effect of this function is not evident unless you use it in combination with other
transform functions such as rotate and the perspective, as shown in the example below.

Example
Try this code »
.container{
width: 125px;
height: 125px;
perspective: 300px;
border: 4px solid #6486ab;
background: #e9eef3;
}
.transformed {
-webkit-transform: scale3d(1, 1, 2) rotate3d(1, 0, 0, 60deg); /*
Chrome, Safari, Opera */
transform: scale3d(1, 1, 2) rotate3d(1, 0, 0, 60deg); /* Standard
syntax */
}
The function scale3d(1, 1, 2) scales the elements along the Z-axis and the
function rotate3d(1, 0, 0, 60deg) rotates the image along the X-axis by the angle 60
degrees.
The matrix3d() Function
The matrix3d() function can perform all of the 3D transformations such as translate, rotate,
and scale at once. It takes 16 parameters in the form of a 4×4 transformation matrix.

Here is an example of performing the 3D transformation using the matrix3d() function.

Example
Try this code »
.container{
width: 125px;
height: 125px;
perspective: 300px;
border: 4px solid #d14e46;
background: #fddddb;
}
.transformed {
-webkit-transform: matrix3d(0.359127, -0.469472, 0.806613, 0,
0.190951, 0.882948, 0.428884, 0, -0.913545, 0, 0.406737, 0, 0, 0, 0, 1);
/* Chrome, Safari, Opera */
transform: matrix3d(0.359127, -0.469472, 0.806613, 0, 0.190951,
0.882948, 0.428884, 0, -0.913545, 0, 0.406737, 0, 0, 0, 0, 1); /* Standard
syntax */
}
However, when performing more than one transformation at once, it is more convenient to
use the individual transformation function and list them in order, like this:

Example
Try this code »
.container{
width: 125px;
height: 125px;
perspective: 300px;
border: 4px solid #a2b058;
background: #f0f5d8;
}
.transformed {
-webkit-transform: translate3d(0, 0, 60px) rotate3d(0, 1, 0, -60deg)
scale3d(1, 1, 2); /* Chrome, Safari, Opera */
transform: translate3d(0, 0, 60px) rotate3d(0, 1, 0, -60deg)
scale3d(1, 1, 2); /* Standard syntax */
}
3D Transform Functions
The following table provides a brief overview of all the 3D transformation functions.

Function Description

translate3d(tx,ty,tz) Moves the element by the given amount along


the X, Y & Z-axis.

translateX(tx) Moves the element by the given amount along


the X-axis.

translateY(ty) Moves the element by the given amount along


the Y-axis.

translateZ(tz) Moves the element by the given amount along


the Z-axis.

rotate3d(x,y,z, a) Rotates the element in 3D space by the angle


specified in the last parameter, around the [x,y,z]
direction vector.

rotateX(a) Rotates the element by the given angle around


the X-axis.

rotateY(a) Rotates the element by the given angle around


the Y-axis.

rotateZ(a) Rotates the element by the given angle around


the Z-axis.

scale3d(sx,sy,sz) Scales the element by the given amount along the


X, Y and Z-axis. The
function scale3d(1,1,1) has no effect.

scaleX(sx) Scales the element along the X-axis.

scaleY(sy) Scales the element along the Y-axis.

scaleZ(sz) Scales the element along the Z-axis.


Function Description

matrix3d(n,n,n,n,n,n, n,n,n,n,n,n,n,n,n,n) Specifies a 3D transformation in the form of a 4×4


transformation matrix of 16 values.

perspective(length) Defines a perspective view for a 3D transformed


element. In general, as the value of this function
increases, the element will appear further away
from the viewer.

CSS3 Transitions
The CSS3 transition feature allows the changes in CSS property values to occur smoothly over
a specified duration.

Understanding CSS3 Transitions


Normally when the value of a CSS property changes, the rendered result is instantly updated.
A common example is changing the background color of a button on mouse hover. In a
normal scenario the background color of the button is changes immediately from the old
property value to the new property value when you place the cursor over the button.

CSS3 introduces a new transition feature that allows you to animate a property from the old
value to the new value smoothly over time. The following example will show you how to
animate the background-color of an HTML button on mouse hover.

Example
Try this code »
button {
background: #fd7c2a;
/* For Safari 3.0+ */
-webkit-transition-property: background;
-webkit-transition-duration: 2s;
/* Standard syntax */
transition-property: background;
transition-duration: 2s;
}
button:hover {
background: #3cc16e;
}
To make the transition occur, you must specify at least two things — the name of the CSS
property to which you want to apply the transition effect using the transition-property CSS
property, and the duration of the transition effect (greater than 0) using the transition-
duration CSS property. However, all the other transition properties are optional, as their
default values don't prevent a transition from happening.

Note: Not all CSS properties are animatable. In general, any CSS property that accepts values
that are numbers, lengths, percentages, or colors is animatable.

Performing Multiple Transitions


Each of the transition properties can take more than one value, separated by commas, which
provides an easy way to define multiple transitions at once with different settings.

Example
Try this code »
button {
background: #fd7c2a;
border: 3px solid #dc5801;
/* For Safari 3.0+ */
-webkit-transition-property: background, border;
-webkit-transition-duration: 1s, 2s;
/* Standard syntax */
transition-property: background, border;
transition-duration: 1s, 2s;
}
button:hover {
background: #3cc16e;
border-color: #288049;
}

Transition Shorthand Property


There are many properties to consider when applying the transitions. However, it is also
possible to specify all the transition properties in one single property to shorten the code.

The transition property is a shorthand property for setting all the individual transition
properties (i.e., transition-property, transition-duration, transition-timing-function,
and transition-delay) at once in the listed order.

It's important to stick to this order for the values, when using this property.

Example
Try this code »
button {
background: #fd7c2a;
-webkit-transition: background 2s ease-in 0s; /* For Safari 3.0+ */
transition: background 2s ease-in 0s; /* Standard syntax */
}
button:hover {
background: #3cc16e;
}
Note: If any value is missing or not specified, the default value for that property will be used
instead. That means, if the value for transition-duration property is missing, no transition
will occur, because its default value is 0.

CSS3 Transition Properties


The following table provides a brief overview of all the transition properties:

Property Description

transition A shorthand property for setting all the four individual transition properties
in a single declaration.

transition-delay Specifies when the transition will start.

transition-duration Specifies the number of seconds or milliseconds a transition animation


should take to complete.

transition-property Specifies the names of the CSS properties to which a transition effect
should be applied.

transition-timing-function Specifies how the intermediate values of the CSS properties being affected
by a transition will be calculated.

CSS3 Animations
The CSS3 animations feature allows you to create keyframe animations.
Creating CSS3 Animations
In the previous chapter you've seen how to do simple animations like animating a property
from one value to another via CSS3 transitions feature. However, the CSS3 transitions provide
little control on how the animation progresses over time. The CSS3 animations take it a step
further with keyframe-based animations that allow you to specify the changes in CSS
properties over time as a set of keyframes, like flash animations. Creating CSS animations is a
two step process, as shown in the example below:

 The first step of building a CSS animation is to defining individual keyframes and naming
an animation with a keyframes declaration.
 The second step is referencing the keyframes by name using the animation-name property
as well as adding animation-duration and other optional animation properties to control the
animation's behavior.

However, it is not necessary to define the keyframes rules before referencing or applying it.
The following example will show you how to animate a <div> box horizontally from one
position to another using the CSS3 animation feature.

Example
Try this code »
.box {
width: 50px;
height: 50px;
background: red;
position: relative;
/* Chrome, Safari, Opera */
-webkit-animation-name: moveit;
-webkit-animation-duration: 2s;
/* Standard syntax */
animation-name: moveit;
animation-duration: 2s;
}

/* Chrome, Safari, Opera */


@-webkit-keyframes moveit {
from {left: 0;}
to {left: 50%;}
}

/* Standard syntax */
@keyframes moveit {
from {left: 0;}
to {left: 50%;}
}
You must specify at least two properties animation-name and the animation-duration (greater than
0), to make the animation occur. However, all the other animation properties are optional, as
their default values don't prevent an animation from happening.

Note: Not all CSS properties are animatable. In general, any CSS property that accepts values
that are numbers, lengths, percentages, or colors is animatable.

Defining Keyframes
Keyframes are used to specify the values for the animating properties at various stages of the
animation. Keyframes are specified using a specialized CSS at-rule — @keyframes. The keyframe
selector for a keyframe style rule starts with a percentage (%) or the keywords from (same as
0%) or to (same as 100%). The selector is used to specify where a keyframe is constructed
along the duration of the animation.

Percentages represent a percentage of the animation duration, 0% represents the starting


point of the animation, 100% represents the end point, 50% represents the midpoint and so
on. That means, a 50% keyframe in a 2s animation would be 1s into an animation.

Example
Try this code »
.box {
width: 50px;
height: 50px;
margin: 100px;
background: red;
position: relative;
left: 0;
/* Chrome, Safari, Opera */
-webkit-animation-name: shakeit;
-webkit-animation-duration: 2s;
/* Standard syntax */
animation-name: shakeit;
animation-duration: 2s;
}

/* Chrome, Safari, Opera */


@-webkit-keyframes shakeit {
12.5% {left: -50px;}
25% {left: 50px;}
37.5% {left: -25px;}
50% {left: 25px;}
62.5% {left: -10px;}
75% {left: 10px;}
}

/* Standard syntax */
@keyframes shakeit {
12.5% {left: -50px;}
25% {left: 50px;}
37.5% {left: -25px;}
50% {left: 25px;}
62.5% {left: -10px;}
75% {left: 10px;}
}

Animation Shorthand Property


There are many properties to consider when creating the animations. However, it is also
possible to specify all the animations properties in one single property to shorten the code.

The animation property is a shorthand property for setting all the individual animation
properties at once in the listed order. For example:

Example
Try this code »
.box {
width: 50px;
height: 50px;
background: red;
position: relative;
/* Chrome, Safari, Opera */
-webkit-animation: repeatit 2s linear 0s infinite alternate;
/* Standard syntax */
animation: repeatit 2s linear 0s infinite alternate;
}

/* Chrome, Safari, Opera */


@-webkit-keyframes repeatit {
from {left: 0;}
to {left: 50%;}
}

/* Standard syntax */
@keyframes repeatit {
from {left: 0;}
to {left: 50%;}
}
Note: If any value is missing or not specified, the default value for that property will be used
instead. That means, if the value for animation-duration property is missing, no transition will
occur, because its default value is 0.
CSS3 Animation Properties.
The following table provides a brief overview of all the animation-related properties.

Property Description

animation A shorthand property for setting all the animation properties in single
declaration.

animation-name Specifies the name of @keyframes defined animations that should be applied
to the selected element.

animation-duration Specifies how many seconds or milliseconds that an animation takes to


complete one cycle of the animation.

animation-timing-function Specifies how the animation will progress over the duration of each cycle i.e.
the easing functions.

animation-delay Specifies when the animation will start.

animation-iteration-count Specifies the number of times an animation cycle should be played before
stopping.

animation-direction Specifies whether or not the animation should play in reverse on alternate
cycles.

animation-fill-mode Specifies how a CSS animation should apply styles to its target before and
after it is executing.

animation-play-state Specifies whether the animation is running or paused.

@keyframes Specifies the values for the animating properties at various points during the
animation.

CSS3 Multi-Column Layouts


With CSS3, you can split the text content of an element in multiple columns.
Creating Multi-Column Layouts
The CSS3 has introduced the multi-column layout module for creating multiple column
layouts in an easy and efficient way. Now you can create layouts like you see in magazines
and newspapers without using the floating boxes. Here is a simple example of splitting some
text into three columns using the CSS3 multiple column layout feature.

Example
Try this code »
p {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3; /* Standard syntax */
}

Setting Column Count or Width


The CSS properties column-count and column-width control whether and how many columns will
appear. The column-count property sets the number of columns inside the multicol element,
whereas the column-width property sets the desired width of the columns.

Example
Try this code »
p {
-webkit-column-width: 150px; /* Chrome, Safari, Opera */
-moz-column-width: 150px; /* Firefox */
column-width: 150px; /* Standard syntax */
}
Note: The column-width describes the optimal width of the column. However, the actual column
width may be wider or narrower according to the space available. This property should not be
used with the column-count property.

Setting Column Gap


You can control the gap between columns using the column-gap property. The same gap is
applied between each column. The default gap is normal which is equivalent to 1em.

Example
Try this code »
p {
/* Chrome, Safari, Opera */
-webkit-column-count: 3;
-webkit-column-gap: 100px;
/* Firefox */
-moz-column-count: 3;
-moz-column-gap: 100px;
/* Standard syntax */
column-count: 3;
column-gap: 100px;
}

Setting Column Rules


You can also add a line between the columns i.e. the rule using the column-rule property. It is a
shorthand property for setting width, style, and color of the rule in a single declaration.
The column-rule property takes the same values as border and outline.

Example
Try this code »
p {
/* Chrome, Safari, Opera */
-webkit-column-count: 3;
-webkit-column-gap: 100px;
-webkit-column-rule: 2px solid red;
/* Firefox */
-moz-column-count: 3;
-moz-column-gap: 100px;
-moz-column-rule: 2px solid red;
/* Standard syntax */
column-count: 3;
column-gap: 100px;
column-rule: 2px solid red;
}
Note: The width of column rule does not affect the width of column boxes, but if a column
rule is wider than the gap, the adjacent column boxes will overlap the rule.

CSS3 Multiple Columns Properties


The following table provides a brief overview of all the multiple columns properties:

Property Description

column-count Specifies the number of columns inside a multi-column element.

column-fill Specifies how content is spread across columns.


Property Description

column-gap Specifies the gap between the columns.

column-rule Specifies a straight line or rule, to be drawn between each column.

column-rule-color Specifies the color of the rule between columns.

column-rule-style Specifies the style of the rule between columns.

column-rule-width Specifies the width of the rule between columns.

column-span Specifies how many columns an element spans across.

column-width Specifies the optimal width of the columns.

columns A shorthand property for setting both the column-width and the column-
count properties at the same time.

CSS3 Box Sizing


With CSS3 box sizing feature you can control element's effective width.

Redefining Box Width with Box-Sizing


By default, the actual width or height of an element's box visible/rendered on a web page
depends on its width or height, padding and border property. For example, if you apply
some padding and border on a <div> element with 100% width the horizontal scrollbar will
appear, as you can see in the example below.

Example
Try this code »
.box {
width: 100%;
padding: 20px;
border: 5px solid #f08080;
}
This is very common problem that web designers are facing for a long time. But, CSS3
introduces the box-sizing property to solve this problem and make the CSS layouts much
more simple and intuitive. The box-sizing property alter the default CSS box model in such a
way that, any padding or border specified on the element is laid out and drawn inside of the
content area, so that the rendered width and height of the element is equal to the specified
CSS width and height properties.

Example
Try this code »
.box {
width: 100%;
padding: 20px;
border: 5px solid #f08080;
box-sizing: border-box;
}
If you see the output of this example, you will find the scroll bar has disappeared.

Note: When using the CSS box-sizing property the resulting width and height of the content
area are calculated by subtracting the border and padding widths of the respective sides from
the specified width and height properties.

Creating Layouts with Box-Sizing


With the CSS box-sizing property creating the multiple columns layout using percentages
becomes very simple. Now you don't have to worry about the final size of the element's box
while adding the padding or border on them.

The following example will create a two column layout where each column has equal width
and are placed side-by-side using the float property.

Example
Try this code »
.box {
width: 50%;
padding: 20px;
background: #f2f2f2;
float: left;
box-sizing: border-box;
}
Similarly, you create more complex layouts using this simple technique.

Example
Try this code »
.box {
width: 30%;
padding: 20px;
margin-left: 5%;
background: #f2f2f2;
float: left;
box-sizing: border-box;
}
.box:first-child {
margin-left: 0;
}

CSS3 Flexible Box Layouts


CSS3 flexible Box, or flexbox is a new layout model for creating the more flexible user
interface design.

Understanding the Flex Layout Model


Flexible box, commonly referred to as flexbox, is a new layout model introduced in CSS3 for
creating the flexible user interface design with multiple rows and columns without using the
percentage or fixed length values. The CSS3 flex layout model provides a simple and powerful
mechanism for handling the distributing of space and alignment of content automatically
through stylesheet without interfering the actual markup. The following example demonstrate
how to create a three column layout where each column has equal width and height using the
flex layout model.

Example
Try this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CSS3 Three Equal Flex Column</title>
<style>
.flex-container {
width: 80%;
min-height: 300px;
display: -webkit-flex; /* Safari */
display: flex; /* Standard syntax */
border: 1px solid #808080;
}
.flex-container div {
background: #dbdfe5;
-webkit-flex: 1; /* Safari */
-ms-flex: 1; /* IE 10 */
flex: 1; /* Standard syntax */
}
</style>
</head>
<body>
<div class="flex-container">
<div class="item1">Item 1</div>
<div class="item2">Item 2</div>
<div class="item3">Item 3</div>
</div>
</body>
</html>
If you notice the above example code carefully you'll find we didn't specify any width on the
inner <div> of the .flex-container, but you can see in the output, every column has width which
is exactly equal to the one third of the parent .flex-container element.

How Flex Layout Works


Flexbox consists of flex containers and flex items. A flex container can be created by setting
the display property of an element to either flex (generate block-level flex container) or inline-
flex (generate an inline flex container similar to inline-block). All child elements of flex
container automatically become flex items and are laid out using the flex layout model.
The float, clear, and vertical-align properties have no effect on flex items.

Flex items are positioned inside a flex container along a flex line controlled by the flex-
direction property. By default, there is only one flex line per flex container which has the same
orientation as the inline axis of the current writing mode or text direction. The following
illustration will help you to understand the flex layout terminology.
Controlling Flow inside Flex Container
In the standard CSS box model, the elements normally displayed in the order as they appear
in the underlying HTML markup. Flex layout lets you control the direction of the flow inside a
flex container in such a way that the elements can be laid out in any flow direction leftwards,
rightwards, downwards, or even upwards. The flow of the flex items in a flex container can be
specified using the flex-direction property. The default value of this property is row which is
same as the document's current writing mode or text direction e.g. left-to-right in English
language.

Example
Try this code »
.flex-container {
width: 80%;
min-height: 300px;
/* Safari */
display: -webkit-flex;
-webkit-flex-direction: row-reverse;
/* Standard syntax */
display: flex;
flex-direction: row-reverse;
border: 1px solid #666;
}
Similary, you can disply the flex items inside a flex container in columns instead of row using
the value column for the flex-direction property, like this:

Example
Try this code »
.flex-container {
width: 80%;
min-height: 300px;
/* Safari */
display: -webkit-flex;
-webkit-flex-direction: column;
/* Standard syntax */
display: flex;
flex-direction: column;
}

Controlling the Dimensions of Flex Items


The most important aspect of the flex layout is the ability of flex items to alter their width or
height to fill the available space. This is achieved with the flex property. It is shorthand
property for flex-grow, flex-shrink and flex-basis properties.
A flex container distributes the free space to its items proportional to their flex grow factor, or
shrinks them to prevent overflow proportional to their flex shrink factor.

Example
Try this code »
.flex-container {
width: 80%;
min-height: 300px;
display: -webkit-flex; /* Safari */
display: flex; /* Standard syntax */
}
.flex-container div {
padding: 10px;
background: #dbdfe5;
}
.item1, .item3 {
-webkit-flex: 1; /* Safari */
flex: 1; /* Standard syntax */
}
.item2 {
-webkit-flex: 2; /* Safari */
flex: 2; /* Standard syntax */
}
In the above example, the first and third flex items will occupy 1/4 i.e. 1/(1+1+2) of the free space
each, whereas the second flex item will occupy 1/2 i.e. 2/(1+1+2) of the free space. Similarly, you
can create other flexible layouts using this simple technique.

Note: It is strongly recommended to use the shorthand rather than the individual flex
properties because it resets unspecified components correctly.

Aligning Flex Items within Flex Container


There are four properties justify-content, align-content, align-items and align-self which are
designed to control the alignment of flex items within flex container. The first three of them
apply to flex containers whereas the last one applies to the individual flex items.

Align Flex Items along Main Axis


Flex items can be aligned along the main axis (i.e. in the horizontal direction) of the flex
container using the justify-content property. It is typically used when the flex items do not use
all the space available along the main axis.

The justify-content property accepts the following values:

 flex-start — Default value. Flex items are placed at the start of the main axis.
 flex-end — Flex items are placed at the end of the main axis.
 center — Flex items are placed at the center of the main axis with equal amounts of free
space at both ends. If the leftover free-space is negative i.e. if the items overflow, then the
flex items will overflow equally in both directions.
 space-between — Flex items are distributed evenly along the main axis, where the first
item placed at the main-start edge and the last one placed at the main-end. If items
overflow or there's only one item, this value is equal to flex-start.
 space-around — Flex items are distributed evenly with half-size spaces on either end. If
they overflow or there's only one item, this value is identical to center.

The following example will show you the effect of the different values for justify-
content property on a multiple-column flex container having fixed width.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
border: 1px solid #666;
/* Safari */
display: -webkit-flex;
-webkit-justify-content: space-around;
/* Standard syntax */
display: flex;
justify-content: space-around;
}
.item1 {
width: 75px;
background: #e84d51;
}
.item2 {
width: 125px;
background: #7ed636;
}
.item3 {
width: 175px;
background: #2f97ff;
}

Align Flex Items along Cross Axis


Flex items can be aligned along the cross axis (i.e. in the perpendicular direction) of the flex
container using the align-items or align-self property. However, where the align-items is
applied to the flex container, the align-self property is applied to the individual flex items, and
overrides align-items. Both properties accept the following values:
 flex-start — Flex items are placed at the start of the cross axis.
 flex-end — Flex items are placed at the end of the cross axis.
 center — Flex items are placed at the center of the cross axis with equal amounts of free
space at both ends. If the leftover free-space is negative i.e. if the items overflow, then the
flex items will overflow equally in both directions.
 baseline — The text baseline (or inline axis) of each flex item is aligned with the baseline of
the flex item with the largest font-size.
 stretch — The flex item stretches to fill the current row or column unless prevented by the
minimum and maximum width or height. Default value for align-items property.

The following example will show you the effect of the different values for align-items property
on a multiple-column flex container having fixed height.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
border: 1px solid #666;
/* Safari */
display: -webkit-flex;
-webkit-align-items: center;
/* Standard syntax */
display: flex;
align-items: center;
}
.item1 {
width: 75px;
height: 100px;
background: #e84d51;
}
.item2 {
width: 125px;
height: 200px;
background: #7ed636;
}
.item3 {
width: 175px;
height: 150px;
background: #2f97ff;
}
You can also distribute free space on the cross axis of a multiple-row or multiple-column flex
container. The property align-content is used to align the flex container's lines, for example,
rows within the multiple-row flex container when there is extra space in the cross-axis, similar
to how justify-content aligns individual items within the main-axis.
The align-content property accepts the same values as justify-content, but applies them to the
cross axis rather than the main axis. It also accepts one more value:

 stretch The free space is split equally between all rows or columns increasing their cross
size. If the leftover free-space is negative, this value is identical to flex-start.

The following example will show you the effect of the different values for align-
content property on a multiple-row flex container having fixed height.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
margin: 0 auto;
font-size: 32px;
border: 1px solid #666;
/* Safari */
display: -webkit-flex;
-webkit-flex-flow: row wrap;
-webkit-align-content: space-around;
/* Standard syntax */
display: flex;
flex-flow: row wrap;
align-content: space-around;
}
.flex-container div {
width: 150px;
height: 100px;
background: #dbdfe5;
}

Reordering Individual Flex Items


In addition to altering the flow within a flex container, you can also change the order in which
individual flex items are displayed using the order property. This property accepts positive or
negative integer as value. By default, all flex items are displayed and laid out in the same
order as they appear in the HTML markup as the default value of order is 0.

The following example will show you how to control the order of an individual flex item.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
border: 1px solid #666;
display: -webkit-flex; /* Safari 6.1+ */
display: flex;
}
.flex-container div {
padding: 10px;
width: 130px;
}
.item1 {
background: #e84d51;
-webkit-order: 2; /* Safari 6.1+ */
order: 2;
}
.item2 {
background: #7ed636;
-webkit-order: 1; /* Safari 6.1+ */
order: 1;
}
.item3 {
background: #2f97ff;
-webkit-order: -1; /* Safari 6.1+ */
order: -1;
}
Note: Flex item with the lowest order value laid out first, whereas the item with
highest order value laid out at the end. Items with the same order value are displayed in the
same order a they appear in the source document.

Horizontal and Vertical Center Alignment with


Flexbox
Normally vertical alignment of a content block involves the use of JavaScript or some ugly CSS
tricks. But with flexbox you can easily do this without any adjustments.

The following example will show you how to align a content block vertically and horizontally
in the middle easily with the CSS3 flexible box feature.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
border: 1px solid #666;
display: -webkit-flex; /* Safari 6.1+ */
display: flex; /* Standard syntax */
}
.item {
width: 300px;
padding: 25px;
margin: auto;
background: #f0e68c;
}

Enable Wrapping of Flex Items


By default, flex containers display only a single row or column of flex items. However, you can
use the flex-wrap property on the flex container to control whether its flex items will wrap into
multiple lines or not, if there is not sufficient space for them on one flex line.

The flex-wrap property accept the following values:

 nowrap — Default value. The flex items are placed in a single line. It may cause overflow, if
there is not enough space on the flex line.
 wrap — The flex container breaks its flex items across multiple lines, similar to how text is
broken onto a new line when it is too wide to fit on the current line.
 wrap-reverse — The flex items will wrap, if necessary, but in reverse order i.e. the cross-
start and cross-end directions are swapped.

The following example will show you how to display the flex items in a single or multiple lines
within a flex container using the flex-wrap property.

Example
Try this code »
.flex-container {
width: 500px;
min-height: 300px;
border: 1px solid #666;
/* Safari */
display: -webkit-flex;
-webkit-flex-wrap: wrap;
/* Standard syntax */
display: flex;
flex-wrap: wrap;
}
.flex-container div{
width: 130px;
padding: 10px;
background: #dbdfe5;
}
Note: You can also use the shorthand CSS property flex-flow for setting both the flex-
direction and flex-wrap in a single declaration. It accepts the same values as the individual
properties and the values can be in any order.
CSS3 Filters
The CSS3 filter effects provide an easy way to apply the visual effect to the images.

Understanding the CSS3 Filter Functions


In this chapter we'll discuss about the filter effects introduced in CSS3 that you can use to
perform visual effect operations like blur, balancing contrast or brightness, color saturation
etc. on graphical elements like an image before it is drawn onto the web page.

The filter effects can be applied to the element using the CSS3 filter property, which accept
one or more filter function in the order provided.

filter: blur() | brightness() | contrast() | drop-shadow() | grayscale() | hue-


rotate() | invert() | opacity() | sepia() | saturate() | url();

Warning: The CSS3 filter effects currently not supported in any version of the Internet
Explorer. Older versions of IE supported a non-standard filter property for creating effects
like opacity, but this feature has been deprecated.

The Blur Effect


Photoshop like Gaussian blur effect can be applied to an element using the blur() function.
This function accepts CSS length value as parameter which defines the blur radius. A larger
value will create more blur. If no parameter is provided, then a value 0 is used.

Example
Try this code »
img {
-webkit-filter: blur(5px); /* Chrome, Safari, Opera */
filter: blur(5px);
}
— The output of the above example will look something like this:
blur(0) blur(2px) blur(5px)

Setting the Image Brightness


The brightness() function can be used to set the brightness of an image. A value of 0% will
create an image that is completely black. Whereas, a value of 100% or 1 leaves the images
unchanged. Other values are linear multipliers on the effect.

You can also set the brightness higher than the 100% which results in brighter image. If the
amount parameter is missing, a value of 1 is used. Negative values are not allowed.

Example
Try this code »
img.bright {
-webkit-filter: brightness(200%); /* Chrome, Safari, Opera */
filter: brightness(200%);
}
img.dark {
-webkit-filter: brightness(50%); /* Chrome, Safari, Opera */
filter: brightness(50%);
}
— The output of the above example will look something like this:

brightness(50%) brightness(100%) brightness(200%)


Note: The filter functions that take a value expressed with a percent sign (e.g. 75%) also accept
the value expressed as decimal (like, 0.75). If the value is invalid, the function returns none and
no filter effect will be applied.

Adjusting the Image Contrast


The contrast() function is used to adjust the contrast on an image. A value of 0% will create
an image that is completely black. Whereas, a value of 100% or 1 leaves the image unchanged.
Values over 100% are also allowed which provide results with less contrast. If the amount
parameter is missing or omitted, a value of 1 is used.

Example
Try this code »
img.bright {
-webkit-filter: contrast(200%); /* Chrome, Safari, Opera */
filter: contrast(200%);
}
img.dim {
-webkit-filter: contrast(50%); /* Chrome, Safari, Opera */
filter: contrast(50%);
}
— The output of the above example will look something like this:

contrast(50%) contrast(100%) contrast(200%)

Adding Drop Shadow to Images


You can use the drop-shadow() function to apply the drop shadow effect to the images like
Photoshop. This function is similar to the box-shadow property.

Example
Try this code »
img {
-webkit-filter: drop-shadow(4px 4px 10px orange); /* Chrome, Safari,
Opera */
filter: drop-shadow(4px 4px 10px orange);
}
— The output of the above example will look something like this:

drop-shadow(0) drop-shadow(2px drop-shadow(4px 4px


2px 4px orange) 10px orange)

Note: The first and second parameters of the drop-shadow() function specifies the horizontal
and vertical offset of the shadow respectively, whereas the third parameter specify the blur
radius and the last parameter specifies the shadow color, just like the box-shadow property,
with one exception, the 'inset' keyword is not allowed.

Converting an Image to Grayscale


The images can be converted to grayscale using the grayscale() function. A value of 100% is
completely grayscale. A value of 0% leaves the image unchanged. Values
between 0% and 100% are linear multipliers on the effect. If the amount parameter is missing, a
value of 0 is used.

Example
Try this code »
img.complete-gray {
-webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
filter: grayscale(100%);
}
img.partial-gray {
-webkit-filter: grayscale(50%); /* Chrome, Safari, Opera */
filter: grayscale(50%);
}
— The output of the above example will look something like this:
grayscale(0) grayscale(50%) grayscale(100%)

Applying Hue Rotation on Image


The hue-rotate() function applies a hue rotation on the image. The passed parameter
defines the number of degrees around the color circle the image samples will be adjusted. A
value of 0deg leaves the image unchanged. If the 'angle' parameter is missing, a value
of 0deg is used. There is no maximum value, the effect of values above 360deg wraps around.

Example
Try this code »
img.hue-normal {
-webkit-filter: hue-rotate(150deg); /* Chrome, Safari, Opera */
filter: hue-rotate(150deg);
}
img.hue-wrap {
-webkit-filter: hue-rotate(480deg); /* Chrome, Safari, Opera */
filter: hue-rotate(480deg);
}
— The output of the above example will look something like this:

hue-rotate(0) hue-rotate(150deg) hue-rotate(480deg)


The Invert Effect
The invert effect like Photoshop can be applied to an image with the invert() function. A
value of 100% or 1 is completely inverted. A value of 0% leaves the input unchanged. Values
between 0% and 100% are linear multipliers on the effect. If the 'amount' parameter is missing, a
value of 0 is used. Negative values are not allowed.

Example
Try this code »
img.partially-inverted {
-webkit-filter: invert(80%); /* Chrome, Safari, Opera */
filter: invert(80%);
}
img.fully-inverted {
-webkit-filter: invert(100%); /* Chrome, Safari, Opera */
filter: invert(100%);
}

Applying Opacity to Images


The opacity() function can be used to apply transparency to the images. A value of 0% is
completely transparent. A value of 100% or 1 leaves the image unchanged. Values
between 0% and 100% are linear multipliers on the effect. If the 'amount' parameter is missing, a
value of 1 is used. This function is similar to the opacity property.

Example
Try this code »
img {
-webkit-filter: opacity(80%); /* Chrome, Safari, Opera */
filter: opacity(80%);
}
— The output of the above example will look something like this:
opacity(100%) opacity(80%) opacity(30%)

Applying Sepia Effect to Images


The sepia() function converts the image to sepia. A value of 100% or 1 is completely sepia. A
value of 0% leaves the image unchanged. Values between 0% and 100% are linear multipliers on
the effect. If the 'amount' parameter is missing, a value of 0 is used.

Example
Try this code »
img.complete-sepia {
-webkit-filter: sepia(100%); /* Chrome, Safari, Opera */
filter: sepia(100%);
}
img.partial-sepia {
-webkit-filter: sepia(30%); /* Chrome, Safari, Opera */
filter: sepia(30%);
}
— The output of the above example will look something like this:

sepia(0%) sepia(30%) sepia(100%)

Tip: In photographic terms, sepia toning is a specialized treatment to give a black-and-white


photograph a warmer tone (reddish-brown) to enhance its archival quality.
Adjusting the Saturation of Images
The saturate() function can be used to adjust the saturaion of an image. A value of 0% is
completely un-saturated. A value of 100% leaves the image unchanged. Other values are linear
multipliers on the effect. Values of amount over 100% are also allowed, providing super-
saturated results. If the 'amount' parameter is missing, a value of 1 is used.

Example
Try this code »
img.un-saturated {
-webkit-filter: saturate(0%); /* Chrome, Safari, Opera */
filter: saturate(0%);
}
img.super-saturated {
-webkit-filter: saturate(200%); /* Chrome, Safari, Opera */
filter: saturate(200%);
}
— The output of the above example will look something like this:

saturate(100%) saturate(200%) saturate(0%)

Note: The url() function specifies a filter reference to a specific filter element. For
example, url(commonfilters.svg#foo). If the filter reference to an element that didn't exist
or the referenced element is not a filter element, then the whole filter chain is ignored. No
filter is applied to the element.

CSS3 Media Queries


CSS media queries enable you to format your documents to be presented correctly on
different size of output devices.
Media Queries and Responsive Web Design
Media queries allow you to customize the presentation of your web pages for a specific range
of devices like mobile phones, tablets, desktops, etc. without any change in markups. A media
query consists of a media type and zero or more expressions that match the type and
conditions of a particular media features such as device width or screen resolution.

Since media query is a logical expression it can be resolve to either true or false. The result of
the query will be true if the media type specified in the media query matches the type of
device the document is being displayed on, as well as all expressions in the media query are
satisfied. When a media query is true, the related style sheet or style rules are applied to the
target device. Here's a simple example of the media query for standard devices.

Example
Try this code »
/* Smartphones (portrait and landscape) ---------- */
@media screen and (min-width: 320px) and (max-width: 480px){
/* styles */
}
/* Smartphones (portrait) ---------- */
@media screen and (max-width: 320px){
/* styles */
}
/* Smartphones (landscape) ---------- */
@media screen and (min-width: 321px){
/* styles */
}
/* Tablets, iPads (portrait and landscape) ---------- */
@media screen and (min-width: 768px) and (max-width: 1024px){
/* styles */
}
/* Tablets, iPads (portrait) ---------- */
@media screen and (min-width: 768px){
/* styles */
}
/* Tablets, iPads (landscape) ---------- */
@media screen and (min-width: 1024px){
/* styles */
}
/* Desktops and laptops ---------- */
@media screen and (min-width: 1224px){
/* styles */
}
/* Large screens ---------- */
@media screen and (min-width: 1824px){
/* styles */
}
Tip: Media queries are an excellent way to create responsive layouts. Using media queries you
can customize your website differently for users browsing on devices like smart phones or
tablets without changing the actual content of the page.

Changing Column Width Based on Screen Size


You can use the CSS media query for changing the web page width and related elements to
offer the best viewing experience for the user on different devices.

The following style rules will automatically change the width of the container element based
on the screen or viewport size. For example, if the viewport width is less than 768 pixels it will
cover the 100% of the viewport width, if it is greater than the 768 pixels but less than the 1024
pixels it will be 750 pixels wide, and so on.

Example
Try this code »
.container {
margin: 0 auto;
background: #f2f2f2;
box-sizing: border-box;
}
/* Mobile phones (portrait and landscape) ---------- */
@media screen and (max-width: 767px){
.container {
width: 100%;
padding: 0 10px;
}
}
/* Tablets and iPads (portrait and landscape) ---------- */
@media screen and (min-width: 768px) and (max-width: 1023px){
.container {
width: 750px;
padding: 0 10px;
}
}
/* Low resolution desktops and laptops ---------- */
@media screen and (min-width: 1024px) {
.container {
width: 980px;
padding: 0 15px;
}
}
/* High resolution desktops and laptops ---------- */
@media screen and (min-width: 1280px) {
.container {
width: 1200px;
padding: 0 20px;
}
}
Note: You can use the CSS3 box-sizing property on the elements to create more intuitive and
flexible layouts with much less effort.

Changing Layouts Based on Screen Size


You can also use the CSS media query for making your multi-column website layout more
adaptable and responsive for devices through little customization.

The following style rule will create a two column layout if the viewport size is greater than or
equal to 768 pixels, but if less than that it'll be rendered as one column layout.

Example
Try this code »
.column {
width: 48%;
padding: 0 15px;
box-sizing: border-box;
background: #93dcff;
float: left;
}
.container .column:first-child{
margin-right: 4%;
}
@media screen and (max-width: 767px){
.column {
width: 100%;
padding: 5px 20px;
float: none;
}
.container .column:first-child{
margin-right: 0;
margin-bottom: 20px;
}
}

CSS3 Miscellaneous
Extending User Interface with CSS3
In this chapter we'll discuss about some interesting user interface related CSS3 properties
like resize, outline-offset, etc. that you can use to enhance your web pages.
Resizing Elements
You can make an element resizable horizontally, vertically or on both directions with the
CSS3 resize property. However, this property is typically used to remove the default resizable
behavior form the <textarea> form control.

Example
Try this code »
p, div, textarea {
width: 300px;
min-height: 100px;
overflow: auto;
border: 1px solid black;
}
p {
resize: horizontal;
}
div {
resize: both;
}
textarea {
resize: none;
}

Setting Outline Offset


In the previous section you've learnt how to set different properties for outlines like width,
color and styles. However, CSS3 offer one more property outline-offset for setting the
space between an outline and the border edge of an element. This property can accepts
negative value that means you can also place outline inside an element.

Example
Try this code »
p, div {
margin: 50px;
height: 100px;
background: #000;
outline: 2px solid red;
}
p {
outline-offset: 10px;
}
div {
outline-offset: -15px;
}

You might also like