2 - CSS Notes
2 - CSS 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.
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.
Without further ado, let's get started with the Cascading Style Sheets (CSS).
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.
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.
You can attach external style sheets in two ways — linking and importing.
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.
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.
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 "{}".
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;
}
*/
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.
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.
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;
}
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.
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.
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.
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 provide several properties for styling the background of an element, including coloring
the background, placing images in the background and managing their positioning, etc.
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:
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;
}
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.
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.
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.
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.
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.
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 */
}
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 */
}
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) */
}
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.
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;
}
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.
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.
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.
Example
Try this code »
a:link, a:visited {
text-decoration: none;
}
a:hover, a:active {
text-decoration: underline;
}
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;
}
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.
In the following section we will discuss the properties that can be used to style HTML lists.
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;
}
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.
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;
}
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.
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;
}
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.
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.
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;
}
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.
The following style rules will vertically bottom-align the text inside the <th> elements.
Example
Try this code »
th {
height: 40px;
vertical-align: bottom;
}
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.
Example
Try this code »
table {
border-collapse: separate;
empty-cells: hide;
}
Note: Placing a non-breaking space ( ) 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.
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>
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.
The actual space that an element's box might take on a web page is calculated like this:
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.
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:
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.
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.
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.
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;
}
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:
Unlike CSS margin, values for the padding properties cannot be negative.
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.
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.
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.
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.
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.
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.
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.
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;
}
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:
You can also specify negative margins on an element, e.g., margin: -10px;, margin: -5%;,
etc.
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.
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.
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.
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.
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.
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;
}
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;
}
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.
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.
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.
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.
Unit Description
The em and ex units depend on the font size that's applied to the element.
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).
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
cm centimeters.
mm millimeters.
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.
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.
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.
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.
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;
}
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.
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;
}
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.
Example
Try this code »
h1 {
text-align: center;
}
p {
text-align: left;
}
See tutorial on CSS Text to learn more about text formatting.
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.
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.
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.
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.
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; }
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.
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.
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.
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.
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; }
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.
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");
}
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;
}
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.
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.
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.
handheld Used for small or handheld devices — usually small screen devices such as mobile phones or
PDAs.
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.
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.
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.
Here we will use the same sprite image (mySprite.png) to create our navigation menu.
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>
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;
}
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 */
}
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.
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).
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).
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.
— 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.
Example
Try this code »
div {
float: left;
opacity: 0.7;
border: 1px solid #949781;
}
p {
float: left;
position: relative;
margin-left: -400px;
}
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
The following section will describe you these new border properties of CSS3, for other border
related properties please check out the CSS border tutorial.
Example
Try this code »
.box {
width: 300px;
height: 150px;
background: #ffb6c1;
border: 2px solid #f08080;
border-radius: 20px;
}
CSS3 Color
CSS3 provides several new ways to define a color values.
In the following section we'll discuss about these color model one by one.
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);
}
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.
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.
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.
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.
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'.
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.
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);
}
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);
}
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);
}
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.
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, ...);
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);
}
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.
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);
}
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");
}
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.
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.
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;
The following section will describe you how to apply the shadow on text and elements.
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;
}
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.
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.
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.
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().
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.
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.
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.
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.
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
CSS3 Transitions
The CSS3 transition feature allows the changes in CSS property values to occur smoothly over
a specified duration.
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.
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;
}
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.
Property Description
transition A shorthand property for setting all the four individual transition properties
in a single declaration.
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;
}
/* 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.
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;
}
/* 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;}
}
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;
}
/* 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-timing-function Specifies how the animation will progress over the duration of each cycle i.e.
the easing functions.
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.
@keyframes Specifies the values for the animating properties at various points during the
animation.
Example
Try this code »
p {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3; /* Standard syntax */
}
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.
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;
}
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.
Property Description
columns A shorthand property for setting both the column-width and the column-
count properties at the same time.
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.
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;
}
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.
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;
}
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.
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;
}
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;
}
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.
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;
}
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.
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.
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.
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)
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:
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:
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:
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.
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%)
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:
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%);
}
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%)
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:
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:
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.
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.
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.
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;
}
Example
Try this code »
p, div {
margin: 50px;
height: 100px;
background: #000;
outline: 2px solid red;
}
p {
outline-offset: 10px;
}
div {
outline-offset: -15px;
}