Unit Iii

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

What is CSS?

•CSS stands for Cascading Style Sheets


•CSS describes how HTML elements are to be displayed on screen,
paper, or in other media
•CSS saves a lot of work. It can control the layout of multiple web pages all
at once
•External stylesheets are stored in CSS files

CSS Demo - One HTML Page - Multiple


Styles!
Here we will show one HTML page displayed with four different stylesheets. Click on
the "Stylesheet 1", "Stylesheet 2", "Stylesheet 3", "Stylesheet 4" links below to see
the different styles:

Object 2

Why Use CSS?


CSS is used to define styles for your web pages, including the design, layout and
variations in display for different devices and screen sizes.

CSS Solved a Big Problem


HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of large
websites, where fonts and color information were added to every single page,
became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
CSS removed the style formatting from the HTML page!

If you don't know what HTML is, we suggest that you read our HTML Tutorial.

CSS Saves a Lot of Work!


The style definitions are normally saved in external .css files.
With an external stylesheet file, you can change the look of an entire website by
changing just one file!
CSS

CSS Syntax
A CSS rule-set consists of a selector and a declaration block:

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces.

Example

In this example all <p> elements will be center-aligned, with a red text color:

p {
color: red;
text-align: center;
}

CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a later date.
Comments are ignored by browsers.

Example

A CSS comment starts with /* and ends with */. Comments can also span multiple lines:

p {
color: red;
/* This is a single-line comment */
text-align: center;
}
CSS Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
•Simple selectors (select elements based on name, id, class)
•Combinator selectors (select elements based on a specific relationship
between them)
•Pseudo-class selectors (select elements based on a certain state)
•Pseudo-elements selectors (select and style a part of an element)
•Attribute selectors (select elements based on an attribute or attribute value)
This page will explain the most basic CSS selectors.

The CSS element Selector


The element selector selects HTML elements based on the element name.

Example

Here, all <p> elements on the page will be center-aligned, with a red text color:

p {
text-align: center;
color: red;
}

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one
unique element!
To select an element with a specific id, write a hash (#) character, followed by the id
of the element.

Example

The CSS rule below will be applied to the HTML element with id="para1":
#para1 {
text-align: center;
color: red;
}

Note: An id name cannot start with a number!

Object 1

The CSS class Selector


The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the
class name.

Example

In this example all HTML elements with class="center" will be red and center-
aligned:

.center {
text-align: center;
color: red;
}

You can also specify that only specific HTML elements should be affected by a class.

Example

In this example only <p> elements with class="center" will be center-aligned:


p.center {
text-align: center;
color: red;
}

HTML elements can also refer to more than one class.

Example

In this example the <p> element will be styled according to class="center" and to
class="large":

< p class="center large">This paragraph refers to two classes.</p>

Note: A class name cannot start with a number!

The CSS Universal Selector


The universal selector (*) selects all HTML elements on the page.

Example

The CSS rule below will affect every HTML element on the page:

* {
text-align: center;
color: blue;
}

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):

h1 {
text-align: center;
color: red;
}

h2 {
text-align: center;
color: red;
}

p {
text-align: center;
color: red;
}

It will be better to group the selectors, to minimize the code.


To group selectors, separate each selector with a comma.

Example

In this example we have grouped the selectors from the code above:

h1, h2, p {
text-align: center;
color: red;
}

All CSS Simple Selectors


Selector Example Example description
.class .intro Selects all elements with class="intro"
#id #firstname Selects the element with id="firstname"
* * Selects all elements
element p Selects all <p> elements
element,element,.. div, p Selects all <div> elements and all <p> elements
When a browser reads a style sheet, it will format the HTML document
according to the information in the style sheet.

Three Ways to Insert CSS


There are three ways of inserting a style sheet:
•External CSS
•Internal CSS
•Inline CSS

External CSS
With an external style sheet, you can change the look of an entire website by
changing just one file!
Each HTML page must include a reference to the external style sheet file inside the
<link> element, inside the head section.

Example

External styles are defined within the <link> element, inside the <head> section of
an HTML page:

< !DOCTYPE html>


<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

An external style sheet can be written in any text editor, and must be saved with
a .css extension.
The external .css file should not contain any HTML tags.
Here is how the "mystyle.css" file looks like:
"mystyle.css"
body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}

Note: Do not add a space between the property value and the unit (such as margin-
left: 20 px;). The correct way is: margin-left: 20px;

Object 3

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.

Example

Internal styles are defined within the <style> element, inside the <head> section of
an HTML page:

< !DOCTYPE html>


<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style
attribute can contain any CSS property.

Example

Inline styles are defined within the "style" attribute of the relevant element:

< !DOCTYPE html>


<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>


<p style="color:red;">This is a paragraph.</p>

</body>
</html>

Tip: An inline style loses many of the advantages of a style sheet (by mixing content
with presentation). Use this method sparingly.
Multiple Style Sheets
If some properties have been defined for the same selector (element) in different
style sheets, the value from the last read style sheet will be used.

Assume that an external style sheet has the following style for the <h1> element:

h1 {
color: navy;
}

Then, assume that an internal style sheet also has the following style for the
<h1> element:

h1 {
color: orange;
}

Example

If the internal style is defined after the link to the external style sheet, the <h1>
elements will be "orange":

< head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>

Example

However, if the internal style is defined before the link to the external style sheet,
the <h1> elements will be "navy":
< head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Cascading Order
What style will be used when there is more than one style specified for an HTML
element?
All the styles in a page will "cascade" into a new "virtual" style sheet by the following
rules, where number one has the highest priority:
1.Inline style (inside an HTML element)
2.External and internal style sheets (in the head section)
3.Browser default
So, an inline style has the highest priority, and will override external and internal
styles and browser defaults.
CSS Backgrounds

The CSS background properties are used to define the


background effects for elements.
CSS background properties:
• background-color
• background-image
• background-repeat
• background-attachment
• background-position

CSS background-color
The background-color property specifies the background color of an element.

Example

The background color of a page is set like this:

body {
background-color: lightblue;
}

With CSS, a color is most often specified by:


•a valid color name - like "red"
•a HEX value - like "#ff0000"
•an RGB value - like "rgb(255,0,0)"
Look at CSS Color Values for a complete list of possible color values.

Example

Here, the <h1>, <p>, and <div> elements will have different background colors:
h1 {
background-color: green;
}

div {
background-color: lightblue;
}

p {
background-color: yellow;
}

Object 4

CSS background-image
The background-image property specifies an image to use as the background of an
element.
By default, the image is repeated so it covers the entire element.

Example

The background image for a page can be set like this:

body {
background-image: url("paper.gif");
}
Example

This example shows a bad combination of text and background image. The text is
hardly readable:

body {
background-image: url("bgdesert.jpg");
}

Note: When using a background image, use an image that does not disturb the text.

CSS background-repeat
By default, the background-image property repeats an image both horizontally and
vertically.
Some images should be repeated only horizontally or vertically, or they will look
strange, like this:

Example
body {
background-image: url("gradient_bg.png");
}

If the image above is repeated only horizontally (background-repeat: repeat-x;),


the background will look better:

Example
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}

Tip: To repeat an image vertically, set background-repeat: repeat-y;


CSS background-repeat: no-repeat
Showing the background image only once is also specified by the background-
repeat property:

Example

Show the background image only once:

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
}

In the example above, the background image is placed in the same place as the
text. We want to change the position of the image, so that it does not disturb the
text too much.

CSS background-position
The background-position property is used to specify the position of the
background image.

Example

Position the background image in the top-right corner:

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
CSS background-attachment
The background-attachment property specifies whether the background image
should scroll or be fixed (will not scroll with the rest of the page):

Example

Specify that the background image should be fixed:

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: fixed;
}

Example

Specify that the background image should scroll with the rest of the page:

body {
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
background-attachment: scroll;
}

CSS background - Shorthand property


To shorten the code, it is also possible to specify all the background properties in one
single property. This is called a shorthand property.
The shorthand property for background is background.

Example

Use the shorthand property to set all the background properties in one declaration:
body {
background: #ffffff url("img_tree.png") no-repeat right top;
}

When using the shorthand property the order of the property values is:
•background-color
•background-image
•background-repeat
•background-attachment
•background-position
It does not matter if one of the property values is missing, as long as the other ones
are in this order.

All CSS Background Properties


Property Description
background Sets all the background properties in one declaration
Sets whether a background image is fixed or scrolls with the rest of the
background-attachment
page
background-clip Specifies the painting area of the background
background-color Sets the background color of an element
background-image Sets the background image for an element
background-origin Specifies where the background image(s) is/are positioned
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated
background-size Specifies the size of the background image(s)
CSS Fonts

The CSS font properties define the font family, boldness, size, and the style of a
text.

Difference Between Serif and Sans-serif


Fonts

CSS Font Families


In CSS, there are two types of font family names:
•generic family - a group of font families with a similar look (like "Serif" or
"Monospace")
•font family - a specific font family (like "Times New Roman" or "Arial")

Generic
Font family Description
family
Times New
Serif Roman Serif fonts have small lines at the ends on some characters
Georgia
Sans-serif
Arial "Sans" means without - these fonts do not have the lines at
Verdana the ends of characters
Courier New
Monospace Lucida All monospace characters have the same width
Console
Note: On computer screens, sans-serif fonts are considered easier to read than serif
fonts.
Font Family
The font family of a text is set with the font-family property.
The font-family property should hold several font names as a "fallback" system. If
the browser does not support the first font, it tries the next font, and so on.
Start with the font you want, and end with a generic family, to let the browser pick a
similar font in the generic family, if no other fonts are available.
Note: If the name of a font family is more than one word, it must be in quotation
marks, like: "Times New Roman".
More than one font family is specified in a comma-separated list:

Example
p {
font-family: "Times New Roman", Times, serif;
}

For commonly used font combinations, look at our Web Safe Font Combinations.

Object 5

Font Style
The font-style property is mostly used to specify italic text.
This property has three values:
•normal - The text is shown normally
•italic - The text is shown in italics
•oblique - The text is "leaning" (oblique is very similar to italic, but less
supported)
Example
p.normal {
font-style: normal;
}

p.italic {
font-style: italic;
}

p.oblique {
font-style: oblique;
}

Font Size
The font-size property sets the size of the text.
Being able to manage the text size is important in web design. However, you should
not use font size adjustments to make paragraphs look like headings, or headings
look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for
paragraphs.
The font-size value can be an absolute, or relative size.
Absolute size:
•Sets the text to a specified size
•Does not allow a user to change the text size in all browsers (bad for
accessibility reasons)
•Absolute size is useful when the physical size of the output is known
Relative size:
•Sets the size relative to surrounding elements
•Allows a user to change the text size in browsers

Note: If you do not specify a font size, the default size for normal text, like
paragraphs, is 16px (16px=1em).
Set Font Size With Pixels
Setting the text size with pixels gives you full control over the text size:

Example
h1 {
font-size: 40px;
}

h2 {
font-size: 30px;
}

p {
font-size: 14px;
}

Tip: If you use pixels, you can still use the zoom tool to resize the entire page.

Set Font Size With Em


To allow users to resize the text (in the browser menu), many developers use em
instead of pixels.
The em size unit is recommended by the W3C.
1em is equal to the current font size. The default text size in browsers is 16px. So,
the default size of 1em is 16px.
The size can be calculated from pixels to em using this formula: pixels/16=em

Example
h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}

h2 {
font-size: 1.875em; /* 30px/16=1.875em */
}

p {
font-size: 0.875em; /* 14px/16=0.875em */
}
In the example above, the text size in em is the same as the previous example in
pixels. However, with the em size, it is possible to adjust the text size in all browsers.
Unfortunately, there is still a problem with older versions of IE. The text becomes
larger than it should when made larger, and smaller than it should when made
smaller.

Use a Combination of Percent and Em


The solution that works in all browsers, is to set a default font-size in percent for the
<body> element:

Example
body {
font-size: 100%;
}

h1 {
font-size: 2.5em;
}

h2 {
font-size: 1.875em;
}

p {
font-size: 0.875em;
}

Our code now works great! It shows the same text size in all browsers, and allows all
browsers to zoom or resize the text!

Font Weight
The font-weight property specifies the weight of a font:
Example
p.normal {
font-weight: normal;
}

p.thick {
font-weight: bold;
}

Responsive Font Size


The text size can be set with a vw unit, which means the "viewport width".
That way the text size will follow the size of the browser window:

Hello World
Resize the browser window to see how the font size scales.

Example
< h1 style="font-size:10vw">Hello World</h1>

Viewport is the browser window size. 1vw = 1% of viewport width. If the viewport is
50cm wide, 1vw is 0.5cm.

Font Variant
The font-variant property specifies whether or not a text should be displayed in a
small-caps font.
In a small-caps font, all lowercase letters are converted to uppercase letters.
However, the converted uppercase letters appears in a smaller font size than the
original uppercase letters in the text.
Example
p.normal {
font-variant: normal;
}

p.small {
font-variant: small-caps;
}

More Examples
All the font properties in one declaration
This example demonstrates how to use the shorthand property for setting all of the
font properties in one declaration.

All CSS Font Properties


Property Description
font Sets all the font properties in one declaration
font-family Specifies the font family for text
font-size Specifies the font size of text
font-style Specifies the font style for text
font-variant Specifies whether or not a text should be displayed in a small-caps font
font-weight Specifies the weight of a font
CSS Text

TEXT FORMATTING
This text is styled with some of the text formatting
properties. The heading uses the text-align, text-transform,
and color properties. The paragraph is indented, aligned, and
t h e s p a c e b e t w e e n c h a r a c t e r s i s s p e c i fi e d . T h e u n d e r l i n e i s
r e m o v e d f r o m t h i s c o l o r e d " Tr y i t Yo u r s e l f " l i n k .

Text Color
The color property is used to set the color of the text. The color is specified by:
•a color name - like "red"
•a HEX value - like "#ff0000"
•an RGB value - like "rgb(255,0,0)"
Look at CSS Color Values for a complete list of possible color values.
The default text color for a page is defined in the body selector.

Example
body {
color: blue;
}

h1 {
color: green;
}

Note: For W3C compliant CSS: If you define the color property, you must also
define the background-color.
Text Alignment
The text-align property is used to set the horizontal alignment of a text.
A text can be left or right aligned, centered, or justified.
The following example shows center aligned, and left and right aligned text (left
alignment is default if text direction is left-to-right, and right alignment is default if
text direction is right-to-left):

Example
h1 {
text-align: center;
}

h2 {
text-align: left;
}

h3 {
text-align: right;
}

When the text-align property is set to "justify", each line is stretched so that every
line has equal width, and the left and right margins are straight (like in magazines
and newspapers):

Example
div {
text-align: justify;
}

Object 6
Text Decoration
The text-decoration property is used to set or remove decorations from text.
The value text-decoration: none; is often used to remove underlines from links:

Example
a {
text-decoration: none;
}

The other text-decoration values are used to decorate text:

Example
h1 {
text-decoration: overline;
}

h2 {
text-decoration: line-through;
}

h3 {
text-decoration: underline;
}

Note: It is not recommended to underline text that is not a link, as this often
confuses the reader.

Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in
a text.
It can be used to turn everything into uppercase or lowercase letters, or capitalize
the first letter of each word:
Example
p.uppercase {
text-transform: uppercase;
}

p.lowercase {
text-transform: lowercase;
}

p.capitalize {
text-transform: capitalize;
}

Text Indentation
The text-indent property is used to specify the indentation of the first line of a
text:

Example
p {
text-indent: 50px;
}

Letter Spacing
The letter-spacing property is used to specify the space between the characters
in a text.
The following example demonstrates how to increase or decrease the space
between characters:

Example
h1 {
letter-spacing: 3px;
}
h2 {
letter-spacing: -3px;
}

Line Height
The line-height property is used to specify the space between lines:

Example
p.small {
line-height: 0.8;
}

p.big {
line-height: 1.8;
}

Text Direction
The direction property is used to change the text direction of an element:

Example
p {
direction: rtl;
}

Word Spacing
The word-spacing property is used to specify the space between the words in a
text.
The following example demonstrates how to increase or decrease the space
between words:
Example
h1 {
word-spacing: 10px;
}

h2 {
word-spacing: -5px;
}

Text Shadow
The text-shadow property adds shadow to text.
The following example specifies the position of the horizontal shadow (3px), the
position of the vertical shadow (2px) and the color of the shadow (red):

Example
h1 {
text-shadow: 3px 2px red;
}

More Examples
Disable text wrapping inside an element
This example demonstrates how to disable text wrapping inside an element.
Vertical alignment of an image
This example demonstrates how to set the vertical align of an image in a text.

Tip: Go to our CSS Fonts chapter to learn about how to change fonts, text size and
the style of a text.

All CSS Text Properties


Property Description
color Sets the color of text
direction Specifies the text direction/writing direction
letter-spacing Increases or decreases the space between characters in a text
line-height Sets the line height
text-align Specifies the horizontal alignment of text
text-decoration Specifies the decoration added to text
text-indent Specifies the indentation of the first line in a text-block
text-shadow Specifies the shadow effect added to text
text-transform Controls the capitalization of text
Specifies how overflowed content that is not displayed should be signaled to the
text-overflow
user
Used together with the direction property to set or return whether the text should be
unicode-bidi
overridden to support multiple languages in the same document
vertical-align Sets the vertical alignment of an element
white-space Specifies how white-space inside an element is handled
word-spacing Increases or decreases the space between words in a text
CSS Lists

Unordered
Ordered Lists:
Lists:
•1. Coffee HTML Lists
• Tea
2.
• Coca Cola
3.
and CSS List
•1. Coffee Properties
• Tea
2. In HTML, there are two
• Coca Cola
3. main types of lists:
•unordered lists (<ul>) - the list items are marked with bullets
•ordered lists (<ol>) - the list items are marked with numbers or letters
The CSS list properties allow you to:
•Set different list item markers for ordered lists
•Set different list item markers for unordered lists
•Set an image as the list item marker
•Add background colors to lists and list items

Different List Item Markers


The list-style-type property specifies the type of list item marker.
The following example shows some of the available list item markers:

Example
ul.a {
list-style-type: circle;
}

ul.b {
list-style-type: square;
}

ol.c {
list-style-type: upper-roman;
}

ol.d {
list-style-type: lower-alpha;
}

Note: Some of the values are for unordered lists, and some for ordered lists.

An Image as The List Item Marker


The list-style-image property specifies an image as the list item marker:

Example
ul {
list-style-image: url('sqpurple.gif');
}

Position The List Item Markers


The list-style-position property specifies the position of the list-item markers
(bullet points).
"list-style-position: outside;" means that the bullet points will be outside the list
item. The start of each line of a list item will be aligned vertically. This is default:

•Coffee - A brewed drink prepared from roasted coffee beans...


•Tea
•Coca-cola
"list-style-position: inside;" means that the bullet points will be inside the list item.
As it is part of the list item, it will be part of the text and push the text at the start:

•Coffee - A brewed drink prepared from roasted coffee beans...


•Tea
•Coca-cola

Example
ul.a {
list-style-position: outside;
}
ul.b {
list-style-position: inside;
}

Remove Default Settings


The list-style-type:none property can also be used to remove the
markers/bullets. Note that the list also has default margin and padding. To remove
this, add margin:0 and padding:0 to <ul> or <ol>:

Example
ul {
list-style-type: none;
margin: 0;
padding: 0;
}

List - Shorthand property


The list-style property is a shorthand property. It is used to set all the list
properties in one declaration:

Example
ul {
list-style: square inside url("sqpurple.gif");
}

When using the shorthand property, the order of the property values are:
•list-style-type (if a list-style-image is specified, the value of this property
will be displayed if the image for some reason cannot be displayed)
•list-style-position (specifies whether the list-item markers should appear
inside or outside the content flow)
•list-style-image (specifies an image as the list item marker)
If one of the property values above are missing, the default value for the missing
property will be inserted, if any.

Styling List With Colors


We can also style lists with colors, to make them look a little more interesting.
Anything added to the <ol> or <ul> tag, affects the entire list, while properties
added to the <li> tag will affect the individual list items:

Example
ol {
background: #ff9999;
padding: 20px;
}

ul {
background: #3399ff;
padding: 20px;
}

ol li {
background: #ffe5e5;
padding: 5px;
margin-left: 35px;
}

ul li {
background: #cce5ff;
margin: 5px;
}

Result:

1. Coffee

2. Tea

3. Coca Cola
• Coffee
• Tea

• Coca Cola

More Examples
Customized list with a red left border
This example demonstrates how to create a list with a red left border.
Full-width bordered list
This example demonstrates how to create a bordered list without bullets.
All the different list-item markers for lists
This example demonstrates all the different list-item markers in CSS.

Test Yourself with Exercises!

All CSS List Properties


Property Description
list-style Sets all the properties for a list in one declaration
list-style-image Specifies an image as the list-item marker
list-style-position Specifies the position of the list-item markers (bullet points)
list-style-type Specifies the type of list-item marker

CSS Tables
The look of an HTML table can be greatly improved with CSS:

Countr
Company Contact
y

German
Alfreds Futterkiste Maria Anders
y

Christina
Berglunds snabbköp Sweden
Berglund

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

German
Königlich Essen Philip Cramer
y

Laughing Bacchus
Yoshi Tannamuri Canada
Winecellars

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td> elements:

Example

table, th, td {
border: 1px solid black;
}

Notice that the table in the example above has double borders. This is because both
the table and the <th> and <td> elements have separate borders.

Collapse Table Borders


The border-collapse property sets whether the table borders should be collapsed
into a single border:
Example

table {
border-collapse: collapse;
}

table, th, td {
border: 1px solid black;
}

If you only want a border around the table, only specify the border property for
<table>:

Example

table {
border: 1px solid black;
}

Table Width and Height


Width and height of a table are defined by the width and height properties.
The example below sets the width of the table to 100%, and the height of the <th>
elements to 50px:

Example

table {
width: 100%;
}

th {
height: 50px;
}
Horizontal Alignment
The text-align property sets the horizontal alignment (like left, right, or center) of
the content in <th> or <td>.
By default, the content of <th> elements are center-aligned and the content of
<td> elements are left-aligned.
The following example left-aligns the text in <th> elements:

Example
th {
text-align: left;
}

Vertical Alignment
The vertical-align property sets the vertical alignment (like top, bottom, or
middle) of the content in <th> or <td>.
By default, the vertical alignment of the content in a table is middle (for both <th>
and <td> elements).
The following example sets the vertical text alignment to bottom for <td> elements:

Example

td {
height: 50px;
vertical-align: bottom;
}
Table Padding
To control the space between the border and the content in a table, use
the padding property on <td> and <th> elements:

Example

th, td {
padding: 15px;
text-align: left;
}

Horizontal Dividers
First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300
Add the border-bottom property to <th> and <td> for horizontal dividers:

Example
th, td {
border-bottom: 1px solid #ddd;
}

Hoverable Table
Use the :hover selector on <tr> to highlight table rows on mouse over:

First Name Last Name Savings


Peter Griffin $100
Lois Griffin $150
Joe Swanson $300
Example
tr:hover {background-color: #f5f5f5;}

Striped Tables
First Name Last Name Savings
Peter Griffin $100
Lois Griffin $150
Joe Swanson $300
For zebra-striped tables, use the nth-child() selector and add a background-
color to all even (or odd) table rows:

Example
tr:nth-child(even) {background-color: #f2f2f2;}

Table Color
The example below specifies the background color and text color of <th> elements:

First Name Last Name Savings


Peter Griffin $100
Lois Griffin $150
Joe Swanson $300

Example
th {
background-color: #4CAF50;
color: white;
}
Responsive Table
A responsive table will display a horizontal scroll bar if the screen is too small to
display the full content:

First Last
Points Points Points Points Points Points Points Points Points Points Points Points
Name Name
Jill Smith 50 50 50 50 50 50 50 50 50 50 50 50
Eve Jackson 94 94 94 94 94 94 94 94 94 94 94 94
Adam Johnson 67 67 67 67 67 67 67 67 67 67 67 67
Add a container element (like <div>) with overflow-x:auto around the <table>
element to make it responsive:

Example
< div style="overflow-x:auto;">

<table>
... table content ...
</table>

</div>

Note: In OS X Lion (on Mac), scrollbars are hidden by default and only shown when
being used (even though "overflow:scroll" is set).

More Examples
Make a fancy table
This example demonstrates how to create a fancy table.
Set the position of the table caption
This example demonstrates how to position the table caption.
CSS Table Properties
Property Description
border Sets all the border properties in one declaration
border-collapse Specifies whether or not table borders should be collapsed
border-spacing Specifies the distance between the borders of adjacent cells
caption-side Specifies the placement of a table caption
Specifies whether or not to display borders and background on empty cells in a
empty-cells
table
table-layout Sets the layout algorithm to be used for a table

CSS Box Model

The CSS Box Model


All HTML elements can be considered as boxes. In CSS, the term "box model" is used
when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:
Explanation of the different parts:
•Content - The content of the box, where text and images appear
•Padding - Clears an area around the content. The padding is transparent
•Border - A border that goes around the padding and content
•Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space
between elements.

Example

Demonstration of the box model:

div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}

Width and Height of an Element


In order to set the width and height of an element correctly in all browsers, you need
to know how the box model works.

Important: When you set the width and height properties of an element with CSS,
you just set the width and height of the content area. To calculate the full size of an
element, you must also add padding, borders and margins.

Example

This <div> element will have a total width of 350px:

div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

Here is the calculation:

320px (width)

+ 20px (left + right padding)


+ 10px (left + right border)

+ 0px (left + right margin)

= 350px

The total width of an element should be calculated like this:


Total element width = width + left padding + right padding + left border + right
border + left margin + right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border +
bottom border + top margin + bottom margin

You might also like