CSS (With HTML5) Learn CSS in One Day and Learn It Well
CSS (With HTML5) Learn CSS in One Day and Learn It Well
Well
CSS for Beginners with Hands-On Project
The only book you need to start coding in CSS
immediately
http://www.learncodingfast.com/css
Copyright © 2015
All rights reserved. No part of this publication may be
reproduced, distributed, or transmitted in any form or by
any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written
permission of the publisher, except in the case of brief
quotations embodied in critical reviews and certain other
noncommercial uses permitted by copyright law.
Preface
This book is written to help you learn CSS FAST and learn it
WELL.
The book does not assume any prior background in coding.
If you are an absolute beginner, you'll find that this book
explains complex concepts in an easy to understand
manner. If you are an experienced coder but new to CSS,
this book will provide you with enough depth to start coding
in CSS immediately.
All examples and images in the book are carefully chosen to
demonstrate each concept so that you can gain a deeper
understand of the language. Each CSS chapter also comes
with an exercise at the end of the chapter. The exercises are
designed to help you further strengthen your
understanding. The source code for all the exercises can be
found in the appendix at the end of the book.
In addition, as Richard Branson puts it: "The best way of
learning about anything is by doing". This book comes with
an additional bonus project where you’ll be guided through
the coding of a webpage entirely from scratch. The project
uses concepts covered in the book and gives you a chance
to see how it all ties together.
You can download the bonus project and the source code for
all the exercises at
http://www.learncodingfast.com/css.
Contact Information
I would love to hear from you.
For feedback or queries, you can contact me at
[email protected].
More Books by Jamie
There are a lot of other tags that we can use inside the
<body>...</body> tags, such as the <img> tag for adding
images, the <table> tag for displaying tables and the <ul>
tag for adding a list. We’ll cover these tags in detail later.
To get a feel of how this works, you can download the code
for this chapter from the accompanying website
(http://learncodingfast.com/css). The source code can be
found in the Chapter 2 - Basics of HTML folder. Double click
on the HTML file to launch it.
You will also be guided through the coding of an actual
HTML document when working on the bonus project that
comes with this book. The source code for the project can
be found in the Bonus Project\Answers folder.
When you set the viewport to 300px and you have an image
that is, say, 500 pixels wide, you will only see a portion of
the image as the image’s width is larger than the width of
the viewport. To see the rest of the image, you have to scroll
the page. In contrast, if you set the viewport to 500px, the
entire image will be shown without any scrolling needed. If
you set the viewport to 1000px, the entire image will be
shown too, but it’ll be smaller and occupy only half the
width of the screen.
<title>...</title>
The <title> tag is used for defining the title that the browser
should display on its title bar or on the page's tab.
<style>...</style>
The <style> tag is used to add internal CSS code to our HTML
document. We’ll learn how to do that in Chapter 3.
Example:
<style type=”text/css”>
body {
…
}
</style>
<link>
The <link> tag is used to link to an external resource, most
commonly used to link to an external CSS stylesheet. It does
not require an end tag.
Example:
<link rel="stylesheet" type="text/css" href="mystyle.css">
The rel and type attributes simply tell the browser that you
are linking to a CSS stylesheet. You do not need to modify
them. The only attribute that you need to modify is the href
attribute. This attribute is used to state the path of the CSS
file.
How to Write Paths to External Files
The path of any external file always starts from the current
folder of the HTML document. Suppose we have five folders:
‘User’, ‘Documents’, ‘MyWebsite’, ‘MyCSS’ and ‘MoreCSS’
with the following structure:
User > Documents > MyWebsite > MyCSS > MoreCSS
That is, the ‘User’ folder contains the ‘Documents’ folder,
which in turn contains the ‘MyWebsite’ folder. Within the
‘MyWesbite’ folder, we have the ‘MyCSS’ folder, which
contains the ‘MoreCSS’ folder.
If you are working on a HTML file in ‘MyWebsite’ and you
want to link to ‘mystyle.css’ in the SAME folder, you simply
write href = “mystyle.css”.
However, if ‘mystyle.css’ is in the ‘MyCSS’ folder (one level
down), you have to write href = “MyCSS/mystyle.css”. If it is in
‘MoreCSS’ (two levels down), you have to write href =
“MyCSS/MoreCSS/mystyle.css”
If ‘mystyle.css’ is in the ‘Documents’ folder (one level up),
you have to use ../ to move one level up. You write href =
“../mystyle.css”. If it is in the ‘User’ folder, you have to move
two levels up. You write href = “../../mystyle.css”.
Elements Within the Body Element
Now that we’ve covered the elements within the head
element, let us move on to the body element.
Elements for Adding Content to the Page
First, let us discuss some commonly used elements for
adding content to our webpage. These tags are enclosed
within the <body>...</body> tags.
<p>... </p>
This is the paragraph tag and is used to add text to a page.
Any content within the two tags will be displayed as a
paragraph. By default, most browsers will add a line before
and after a paragraph.
Example:
<p>This is a paragraph</p>
<img>
This <img> tag is for adding images to your webpage. It
requires you to provide some additional information like the
location of the image, its height and width etc. Commonly
used attributes of the <img> tag include:
src:
Stands for “source” and is used to state the path of the
image. The src attribute must be provided.
height:
For specifying the desired display height of the image
width:
For specifying the desired display width of the image
alt:
Stands for “alternate” and is used to specify the text to
display if the image fails to load.
Example:
<img src=”images/myImage.jpg” height=”100px” width=”100px”
alt=”My Image”>
This will insert the image “myImage.jpg” onto the webpage.
The image will be scaled to a size of 100px by 100px. If the
image fails to load, the text “My Image” will be displayed
instead.
<a>...</a>
The <a> tag is used to insert a hyperlink. The most important
attribute for the <a> tag is href which is used to specify the
URL of the page the link goes to.
Example:
<a href=”http://www.google.com”>Click here to go to Google</a>
Output:
Click here to go to Google
Output:
This is the most important
heading.
This is the second most important
heading.
<ol>...</ol> and <li>...</li>
The <ol> tag stands for ordered list and is used to create a
list with numbers or alphabets as list markers.
Example:
<ol>
<li>Chocolate</li>
<li>Strawberry</li>
<li>Vanilla</li>
</ol>
Output:
1. Chocolate
2. Strawberry
3. Vanilla
<ul>...</ul> and <li>...</li>
The <ul> tag stands for unordered list and is similar to the
<ol> tag. However, instead of using numbers or alphabets as
list markers, it uses shapes (such as a dot, or a hollow
circle).
Case Insensitivity
For the most part, CSS selectors and rules are case-
insensitive. Hence, you can either write
div {
Background-color: GREEN;
}
or
DIV {
background-coloR: green;
}
Both will work equally well. The only exception to this case-
insensitivity is when selecting classes and ids.
If we have
<div id= “myID”>Some text</div>
div#myID will select the above element while div#MYID will not.
Order of Precedence
Now that we’ve learnt how to select elements, let us move
on to a very important concept in CSS: order of precedence.
As mentioned earlier, we can apply CSS code to our website
in three different ways. It is common for a programmer to
use more than one way to apply CSS code to a site. For
instance, a website may have CSS rules defined in an
external file AND some additional CSS rules embedded
within its <style>...</style> tags. This may result in more
than one rule being applied to the same element. One of the
most frustrating experience about working with CSS,
especially when you are first starting out, is when you try to
apply a css style to an element and the page simply seems
to ignore your rule. Most of the time, this is due to the order
of precedence. Specifically, this happens when more than
one rule applies to the same element, and another rule has
a higher precedence than the one you are specifying.
Three principles control which CSS rule has a higher
precedence.
Principle 1: The more specific the selector, the higher
the precedence
We won’t go into details about how to calculate the
specificity of a selector. The main point to remember is that
an id is considered to be more specific than a class, and a
class more specific than an element. Let’s consider the code
below:
div { font-size: 10px; }
#myId { font-size: 12px; }
.myClass { font-size: 14px; }
<div id=”myId” class=”myClass”>Some text</div>
Since the <div> element has class=”myClass” and id=”myId”, all
three rules div, #myId and .myClass will apply to the <div>
element. However, as id has the highest precedence, “Some
text” will be displayed with a font size of 12px.
In addition, another point to note about specificity is that
the more detailed your selector, the higher the precedence.
For instance, div#myId has a higher precedence than #myId.
This is because div#myId is considered to be more detailed as
it tells us that myId is an id of the div element. In the sample
code below, the color yellow will be applied.
div { color: red; }
div#myId { color: yellow; }
#myId { color: blue; }
.myClass { color: green; }
<div id=”myId” class=”myClass”>Some text</div>
Principle 2: If no style is specified, elements inherit
styles from their parent container
A child element is an element which lies entirely within the
start and end tags of another element. For instance, in the
code below, <p> is a child element of the <body> element.
Since the font size of <p> is not defined, it’ll inherit this
property from the <body> element for which the property is
defined.
body {
font-size: 1.5em;
}
<body>
<p>Some text</p>
</body>
If the font-size property
is also not defined for the <body>
element, the browser’s default font size will be used.
Principle 3: All else being equal, the last declared
rule wins
Suppose you have the following CSS declaration in your
HTML <head> element.
<head>
<style>
p { font-size: 20px; }
</style>
</head>
Further down the HTML document, you have the following
HTML code, with an inline CSS rule:
<p style=”font-size: 30px;”>Some text</p>
Which rule do you think will be applied to the words “Some
text”?
The correct answer is the inline rule. This is because all
things being equal, the rule that is declared last has the
highest precedence. Since inline CSS is declared within the
HTML code, it is declared later than the embedded CSS
which is declared in the head section. Hence, a font size of
30px will be applied.
Display Inconsistency
Another issue to deal with when working with CSS is the
problem of display inconsistency across browsers. You may
find that your website looks slightly (or drastically) different
in different browsers. Most display issues tend to occur in
older versions of Internet Explorer, although issues can
occur in other browsers too (especially mobile browsers).
Display inconsistencies occur because different browsers
use different layout engines to interpret the site’s CSS code.
For instance, Safari and Chrome use the WebKit engine
while Firefox uses the Gecko engine. One engine may
calculate and display a page differently from another
engine. For instance Trident, the engine used by Internet
Explorer, automatically widens a page’s pixel width for
certain page designs. This can lead to the sidebar being
pushed to the bottom due to insufficient width.
Another problem causing display inconsistency is the lack of
universal support for some CSS properties. Some properties
are not supported by all browsers. You can go to the site
http://www.caniuse.com to check if a certain CSS property is
supported by the browser that you are developing for.
p {
background-color: yellow;
}
This selects all the <p> elements and sets their
background colors to yellow. The line 'This is some text
in the div element.' is not selected because it is not
within any <p>...</p> tags.
p {
background-color: yellow;
}
to
P {
Background-coloR: YELLOW;
}
a[href=”http://www.learncodingfast.com”]
Try it. Only the first link will have a yellow background
now.
a[href=”http://www.learncodingfast.com”]
to
a:hover
p:nth-child(2)
14. Now, let’s try selecting the first letter of all <p>
elements. You use the pseudo-element first-letter to do
that. Change the selector to
p::first-letter
.mySecondClassPara {
text-decoration: underline;
}
p::after{
content: “!”;
}
Chapter 4: CSS Box Model
So far, we’ve covered the basics of HTML and CSS. In this
chapter, we’ll start to do some actual CSS coding.
Specifically, we’ll learn about the CSS box model and look at
how we can modify the look and feel of a box in CSS.
What is the CSS Box Model
All elements in CSS are treated as boxes. CSS boxes consist
of margins, borders, padding, and the actual content as
shown below.
The thick black line is the border. Within the border is the
padding and the actual content. Outside the border is the
margin of the box. The thickness of the padding, border and
margin can all be modified with CSS. To understand how this
box model works, let’s analyze the code below. You can
download this code at http://learncodingfast.com/css.
<!doctype html>
<html>
<head><title>Chapter 4 - CSS Box Model</title>
<style type="text/css">
#box1 {
margin: 20px;
padding: 10px;
border: 5px solid black;
width: 100px;
height: 100px;
text-align: justify;
float: left;
}
#box2 {
margin: 20px;
padding: 50px;
border: 5px solid black;
width: 100px;
height: 100px;
text-align: justify;
float: left;
}
</style></head>
<body>
<div id="box1">Learn CSS in One Day and Learn It Well. CSS is
easy.</div>
<div id="box2">Learn CSS in One Day and Learn It Well. CSS is
easy.</div>
<p>skajd fhadlc vkas j cnl ka jshvn aclaks jdclkasjd ckasj
cnkas djvcn ksa mc nlkasd jn skajd fhadlc vkas j cnl ka jshvn
aclaks jdclkasjd ckasj cnkas djvcn ksa mc nlkasd jn skajd
fhadlc vkas j cnl ka jshvn aclaks jdclkasjd ckasj cnkas djvcn
ksa mc nlkasd jn</p>
</body>
</html>
If you run this code, you’ll get the boxes below. The
gibberish text beside and below the boxes is added to show
the margin.
This code defines two boxes with width and height of 100
pixels. This width and height refers to the dimensions of the
content area only.
The first box (box1) has a padding of 10 pixels (px) around
the content area. Around the padding, it has a solid black
border of 5px. The total width of box1 (including its border) is
100 (content area) +10*2 (padding on both sides) +5*2
(border on both sides) = 130 px. The same applies for the
height.
The second box (box2) has a padding of 50px. Despite box2
being much larger than box1, notice that the text “Learn CSS
in One Day and Learn It Well. CSS is easy.” still occupies the
same area? This is because the content area is determined
by the width and height properties, not by the padding. box2
has a total width of 100+50*2+5*2 = 210px. Its height is
also 210px.
border-radius
The border-radius property is used to create borders with
rounded corners. The value is normally given in pixel or
percentage.
Save the file in the text editor and refresh the page in
the browser. Notice what happens to box1 in each case.
6. Remove the margin rules for box1 and add the 4 lines
below:
margin-top: 25px;
margin-right: 50px;
margin-bottom: 60px;
margin-left: 10px;
7. Remove the margin rules for box1 and add the line
below:
margin: 0 auto;
9. Remove the padding rules for box2 and add the 4 lines
below:
padding-top: 25px;
padding-right: 50px;
padding-bottom: 60px;
padding-left: 10px;
10. Now let's change the border style for box2. Remove
the line border: 5px solid black; from the CSS declaration
of box2 and add each of the following. Notice what
happens to the border in each case:
11. Next, remove the border-style rule for box2 and add
the following:
border-top-style: dotted;
border-left-style: double;
14. Next, we'll try the border shorthand. Remove all the
border properties for box2. Add the following:
to
Chapter 5: Positioning and Floating
Now that we understand the CSS box model, let’s look at
how to use CSS to specify the arrangement of these boxes
on our web pages. In this chapter, we’ll be looking at two of
the most important concepts in CSS: positioning and
floating. Together, these two properties handle the layout of
our web pages.
Positioning
The CSS positioning property allows you to position an
element and specify which element should be on top in case
of an overlap.
There are four methods to position an element. To
understand how the four methods work, I strongly
encourage you to try out the exercise at the end of this
chapter. This is a topic that is difficult to understand without
a hands-on approach.
Static Positioning
The first positioning method is static positioning. Static
doesn't mean much, it just means that the elements are
positioned according to the normal flow of the page. All
HTML elements are positioned using this method by default.
If you want to specify that static positioning be used (for
instance to override another positioning rule for the same
element), you write
position: static;
Relative Positioning
The second method to position an element is the relative
positioning method. This method positions an element
relative to its normal position. Normal position refers to the
default position of the element when no positioning rule is
specified or when static positioning is used.
Suppose we have two boxes, box1 and box2 with no
positioning specified. If we create box2 after box1 in our HTML
code, box2 will be positioned below box1 by default (refer to
code below).
<!DOCTYPE html>
<html>
<head>
<style>
#box1 {
/*Some rules for styling box1*/
}
#box2 {
/*Some rules for styling box2*/
}
</style>
</head>
<body>
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>
</body>
</html>
Now suppose we add the following rules to the CSS
declaration of box2.
position: relative;
left: 150px;
top: 50px;
What we’ve done is change the positioning of box2 to
relative positioning.
The image above shows the position of box2 when relative
positioning is used. A white dotted box is added to show the
original position of box2.
When relative positioning is applied, box2 is moved relative
to its normal position. The line top: 50px; moves the box
50px away from the top of the original position and the line
left: 150px; moves it 150px away from the left.
You can also use the right and bottom properties to position
box2. For instance, bottom: 50px; will move box2 50px up from
the original bottom of box2 while right: 50px; will move it
50px left from the original right edge of box2. In addition,
you can use negative pixels to position the boxes (e.g. left:
-50px)
Try the exercise for Chapter 5 and play around with the
values to see how all these work.
Note that when relative positioning is used, the element can
end up overlapping other elements.
If you want to specify which element should be in front, you
have to use the z-index property. The z-index property works
on any element that has a position of either relative, fixed
or absolute (i.e. not static). An element with greater z-index
value will be positioned in front of an element with a lower
z-index value.
Suppose you have two boxes, greenBox and redBox, and they
overlap each other. If you declare the z-index of greenBox as
z-index: 1;
and the z-index of redBox as
z-index: 2;
redBox will be on top of greenBox as it has a greater z-index
value.
Fixed Positioning
The third positioning method is fixed positioning. As the
name suggests, an element that is positioned using the
fixed method will always stay at its assigned location; it will
not move even when the page is scrolled. Fixed positioning
is commonly used to position social sharing buttons at the
side of a web page. To use fixed positioning, we write
position: fixed;
When using fixed positioning, we can use the top property to
specify the number of pixels the box should be from the top
of the page while the left property specifies the number of
pixels it should be from the left of the page.
In addition to top and left, there are also the right and
bottom properties, which specify the number of pixels the
box should be from the right side and bottom of the page
respectively.
Absolute Positioning
The final method is absolute positioning.
When absolute positioning is used, an element is positioned
relative to the first parent element that has a position other
than static. If no such element is found, it is positioned
relative to the page.
For instance, suppose we have the following HTML code:
<div id="box1">Content in Box 1</div>
<div id="box2">Content in Box 2</div>
and the following CSS declaration:
#box1 {
position: relative;
}
#box2 {
position: absolute;
top: 50px;
left: 150px;
}
Assuming that box2 is not a child element of any element
that has a non static positioning, it’ll be positioned relative
to the page. That is, it is positioned 50px from the top of the
page and 150px from the left.
However, if we change the HTML structure to
<div id="box1">Content in Box 1
<div id="box2">Content in Box 2</div>
</div>
box2 is now a child element of box1. Hence box2 will be
positioned relative to box1. It is now 50px down from the top
and 150px right from the left side of box1.
In a way, absolute positioning is similar to relative
positioning, except that the element is positioned relative to
its parent element instead of its normal position.
Floating
The next CSS property we are going to discuss is floating.
Floating is a technique used to arrange elements on a page.
The idea is similar to putting books onto a bookshelf.
Imagine you have a stack of books of varying thickness and
height and you need to put all the books onto a bookshelf. In
addition, you are not allowed to rearrange the books. That
is, the books must be placed onto the bookshelf in the same
order as they were in the original stack.
To perform this task CSS-style, we’ll start with the top row.
We’ll put the books one by one onto the top row, starting
from left to right. Suppose the top row is almost full and you
have a book that is too thick to fit onto the top row. What do
you do? You’ll move to the next row below it, right? Well,
CSS does it a little differently. CSS will try to fit this ‘book’
onto the same row, below the previous ‘book’, as long as
there is some space below it (refer to Box 5 in the next
diagram). This method of stacking the books is similar to
doing a float: left in CSS.
Alternatively, you can do a float: right in CSS. This is
equivalent to starting from the top row but stacking the
books from right to left.
To see how this works in CSS, suppose we have 7 div boxes
of varying heights and widths that are floated left (refer to
code below):
<!doctype html>
<html>
<head><title>CSS Float</title>
<style type="text/css">
div {
padding: 10px;
border: 1px dashed black;
margin: 5px;
float: left;
}
#box1 {
width: 60px;
height: 100px;
}
#box2 {
width: 100px;
height: 20px;
}
#box3 {
width: 50px;
height: 150px;
}
#box4 {
width: 20px;
height: 50px;
}
#box5 {
width: 150px;
height: 120px;
}
#box6 {
width: 120px;
height: 70px;
}
#box7 {
width: 25px;
height: 80px;
}
</style></head>
<body>
<div id="box1">Box 1</div>
<div id="box2">Box 2</div>
<div id="box3">Box 3</div>
<div id="box4">Box 4</div>
<div id="box5">Box 5</div>
<div id="box6">Box 6</div>
<div id="box7">Box 7</div>
</body>
</html>
If we run this code, we’ll get something like the next image.
position: relative;
top: 50px;
left: 70px;
Play around with different values for the top and left
properties and see what happens to the position of box2.
Try negative values as well. You can also try using the
right and bottom properties.
4. Now change the CSS declaration of #box2 back to
position: relative;
top: 50px;
left: 70px;
position: relative;
z-index: 2;
Scroll the page. 5. The red box does not move as it uses
fixed positioning now.
7. Now change the <div> code for the three boxes to the
following:
4. Now change the rule back to float: left; and add the
code below to the HTML code, just above the </body>
tag.
Refresh the page and observe where the text is. Resize
the browser window to see what happens when the
width of the page is narrow.
Example:
display: none;
Visibility
The CSS visibility property is used to hide an element. You
do that by writing visibility: hidden;.
The difference between visibility: hidden and display: none
is that for the former, the element is hidden but still takes
up space. Using the visibility property is just like wearing
an invisible cloak. The element is still there, even though
you can’t see it.
In contrast, when you use display: none, the element is
essentially removed from the page and the page will display
as if the element does not exist at all.
For instance, suppose the two properties are applied to the
word “magic” in the sentence “This is just like magic. You
can make words disappear.” below:
For visibility: hidden; you’ll get
“This is just like . You can make words disappear.”
For display: none; you’ll get
“This is just like . You can make words disappear.”
Exercise 6
Download the source code for this exercise from
http://learncodingfast.com/css and unzip the file. The source
code for this exercise can be found in the Chapter 6 -
Display and Visibility folder.
Exercise 6.1
1. Open the file Chapter 6 - Display and Visibility.html
concurrently in your browser and text editor.
Chapter 7: Background
In this chapter, we’ll learn how to change the background
properties of an element. These properties include changing
its background color and background image.
For a start, let us first look at how to change the background
color.
Background Color
To declare the background color of an element, we use the
background-color property. Similar to how we specify the
border color of our CSS boxes, we can declare the
background color of an element using one of three
notations: color name, rgb notation or hexadecimal
notation.
Examples:
background-color: green;
background-color: rgb(0, 255, 0);
background-color: #00FF00;
Background Image
If you find it plain to just use color as the background of an
element, you can choose to use an image. CSS allows us
great flexibility in how we want the image to be displayed.
background-image
To use an image as the background, we specify the URL to
the image using the background-image property.
Example:
background-image: url(“image1.jpg”);
background-repeat
By default, the background image is placed at the top-left
corner of the element, and repeated both vertically and
horizontally. If you do not want the background image to be
repeated, you can use the background-repeat property to
change it. The following list shows some commonly used
values for the background-repeat property: repeat
This is the default. Image will be repeated horizontally and
vertically.
repeat-x
Image will only be repeated horizontally.
repeat-y
Image will only be repeated vertically.
no-repeat
Image will not be repeated.
Example:
background-repeat: repeat-x;
background-attachment
The background-attachment property specifies whether the
background image should be fixed or scroll with the page.
The two commonly used values are fixed and scroll. The
default is scroll. Try the exercise at the end of this chapter
to see how this works.
Example:
background-attachment: scroll;
background-position
The background-position property is very useful if you want to
specify which area of the background image you want to
display.
Suppose you have an element with width and height 100px
each. If the background image that you use has width 200px
and height 300px, only a portion of the background image
will be displayed as the image is larger than the size of the
element.
For instance, if you use the image above (200px by 300px)
as the background image of a 100px by 100px element,
only Area A (top left) will be displayed by default. What if
you want to display Area F instead? To do that, you need to
change the value of the background-position property.
The most common way to specify the background-position
value is to use pixels. The syntax is: background-position: xpos
ypos;
To understand how this syntax works, let’s imagine a piece
of cardboard with a 100px by 100px hole in the middle. This
hole in the cardboard represents the HTML element. Now
imagine your background image is underneath that
cardboard. By default, the image will be aligned such that
Area A is shown through the hole in the cardboard. If you
want to display Area F instead, you have to shift the image
(not the cardboard) 100px to the left and 200px up. To
achieve this with CSS, you write: background-position: -100px
-200px;
The first number (-100px) shifts the image horizontally. If
this number is positive, the image is shifted to the right. If
negative, it is shifted to the left.
The second number (-200px) shifts the image vertically. If
this number is positive, the image is shifted down. If
negative, it is shifted up.
The best way to understand this concept is to try the
exercises for this Chapter. I strongly encourage you to do
them before moving on to Chapter 8.
Exercise 7
Download the source code for this exercise from
http://learncodingfast.com/css and unzip the file. The source
code for this exercise can be found in the Chapter 7 -
Background folder.
Exercise 7.1
1. Open the file Chapter 7 - Background.html
concurrently in your browser and text editor.
2. Scroll the page in your browser window. The Learn
Coding Fast logo is set as the background for the body
element. Notice what happens to the logo as you scroll.
font-size
The font-size property sets the size of the text. Font size can
be set with pixels (px), em, percentage (%) or by using
keywords.
Using px
The default font size used on most browsers is 16 pixels. If
you want your site to display with a different font size, you
can specify it like this: font-size: 20px;.
Using em
An em is is equal to the current font size. If the element is
the child of another element, the current font size is the font
size of the parent element. If the element is not a child of
any element, the current font size is the browser’s default
font size. As mentioned above, the default font size used on
most browsers is 16px. Hence by default 1em = 16px.
However, this default font size can be changed by changing
the browser’s setting. For instance, to change the default
font size on Firefox, click on the menu button (the right most
button with three horizontal lines), select “Options’ and
finally select the “Content’ tab. You can then change the
current font size under the ‘Fonts & Colors’ section.
If the user sets the default font size to 20px, 1em becomes
20px. If you want the font size to be 1.5 times the current
font size, you simply write 1.5em. The em is the prefered
unit size used by most developers as the default font size
can be customised by the user.
Using Percentage
Percentage is similar to em. 200% simply means 2 times the
current font size. Hence, 200% = 2em.
Using Keywords
The final way to specify font size is to use keywords.
Commonly used keywords are xx-small, x-small, small, medium
(this is the default), large, x-large and xx-large.
Examples:
font-size: 40px;
font-size: 1.5em;
font-size: 120%;
font-size: large;
font-style
The font-style property is used to specify italic text. The two
common values are normal and italic. Normal will display
text with no italic while italic displays text in italic.
Example:
font-style: italic;
font-weight
The font-weight property is the counterpart of font-style.
While font-style is used to specify italic text, font-weight is
used to specify bold text. Commonly used values include
normal, bold, bolder and lighter. Alternatively, you can also
specify the thickness of the characters using numbers in
multiples of 100, from 100 (thinnest) to 900 (thickest). 400
is the normal thickness, and 700 is the same as bold.
However, note that most web browsers only support normal
and bold font weights. In that case, 100-500 correspond to
normal while 600 and above correspond to bold.
Examples:
font-weight: bold;
font-weight: 300;
Text Properties
CSS text properties allow you to set properties that are not
related to the font of the text. Common properties include
text color, text alignment, text decoration, letter spacing,
word spacing and line height.
color
The CSS color property specifies the color of the text. Similar
to what we learned in Chapter 4 regarding the border-color
property, text color can be specified in one of three ways:
using a color name, a RGB value or a hex value.
Examples:
color: blue;
color: #00ff00;
color: rgb(255,0,0);
text-alignment
The text-alignment property allows us to specify whether we
want text to be centered, or aligned to the left or right, or
justified. The commonly used values are left, right, center
and justify.
Example:
text-align: center;
text-decoration
The text-decoration property is mainly used to specify
whether the text should be decorated with a line. The
commonly used values are none (i.e. just normal text, no
decoration), underline, overline (a line above the text) and
line-through (a line through the text).
This property is commonly used to remove underlines from
hyperlinks. By default, most browsers will display hyperlinks
in blue, with an underline. You can use the code text-
decoration: none; to remove the underline.
Example:
text-decoration: none;
letter-spacing
Letter spacing is used to increase or decrease the spacing
between letters in a word. You specify the amount of
spacing in pixels. To increase the spacing, use a positive
value. To decrease it, use a negative value.
For instance, letter-spacing: 2px; will cause the letters to be
spaced 2 pixels apart. letter-spacing: -1px; will cause the
letters to be cramped together, overlapping each other by 1
pixel.
Example:
letter-spacing: 2px;
word-spacing
Word spacing, on the other hand, is used to increase or
decrease the spacing between words in text. Similar to
letter-spacing, you specify the amount of spacing in pixels,
using positive to increase the spacing and negative to
decrease it.
Example:
word-spacing: 2px;
line-height
Line height is used to set the spacing between each line of
text. This property can be set using a number, a specific
length, or a percentage.
When using a number to specify line-height, the given
number will be multiplied with the current font size to give
the line height. For instance, line-height: 2 will result in a
line height of 32px if the current font size is 16px.
When using length to specify line-height, units such as px
(pixel), em, cm, pt (point, where 1 point = 1/72 of 1in) etc
can be used.
When using percentage, the given percentage will be
multiplied with the current font size to give the line height.
For instance, line-height: 50% will result in a line-height of
8px if the current font size is 16px. Note that line-height
does not alter the font size. A line height of 8px will result in
the lines overlapping each other.
Examples:
line-height: 20px;
line-height: 120%;
To have a better understanding of how each of these
properties work, try the exercise below.
Exercise 8
Download the source code for this exercise from
http://learncodingfast.com/css and unzip the file. The source
code for this exercise can be found in the Chapter 8 - Font
and Text folder.
Exercise 8.1
1. Open the file Chapter 8 - Font and Text.html
concurrently in your browser and text editor.
2. Modify the CSS property font-family and observe what
happens to the sample text. The current font family is
Sans Serif. Try each of the following:
(a) line-height: 2;
(b) line-height: 25px;
(c) line-height: 30%;
Chapter 9: Lists, Links and Navigation
Bars
In this chapter, we’ll be looking at CSS properties for styling
hyperlinks and lists. In addition, we’ll combine both
concepts and discuss how to create navigation bars
commonly seen on web pages. Ready? Let’s first start with
CSS list.
CSS Lists
Recall that in HTML, we can create two different types of list:
ordered list and unordered list? We can style these lists
using CSS list properties.
list-style-type
The list-style-type property allows you to set list item
markers for your lists. List item markers refer to those
bullets/numbers/letters on the left of each list item.
For ordered lists, we can specify the type of numbers or
letters we want to use as markers. For instance, if we want
to use roman numbers (e.g. i, ii, iii) as item markers, we can
write list-style-type: lower-roman;.
In other words, list-style-position: inside will result in more
indentation than list-style-position: outside. The default
position is outside.
Examples:
list-style-position: outside;
list-style
list-style is a shorthand property for setting all the list
properties (i.e. list-style-type, list-style-position and list-
style-image) in one declaration. If any value is missing, the
default value for the missing property will be used.
Examples:
list-style: square inside url("myMarker.gif");
CSS Links
Hyperlinks can be styled using any of the CSS properties
discussed in previous chapters. You can style the
background color using the background-color property. This
will give the link a highlighted appearance. You can also use
the text and font properties covered in Chapter 8 to change
the font size, font style, text color, text decoration etc.
In addition, we can choose to style hyperlinks based on the
state they are in. Links can be in one of four states:
Navigation Bars
Navigation bars are commonly created as an unordered list
in HTML and styled using list and link properties in CSS.
Let’s try creating our own navigation bar. First, we need to
create an unordered list of items for our menu and make the
list items clickable (as hyperlinks).
<ul>
<li><a href=”home.html”>Home</a></li>
<li><a href=”htmltutorial.html”>HTML Tutorial</a></li>
<li><a href=”csstutorial.html”>CSS Tutorial</a></li>
<li><a href=”javascripttutorial.html”>Javascript
Tutorial</a></li>
</ul>
Next, let’s add the following declaration to our CSS style to
remove the default bullet from the list.
ul {
list-style-type: none;
}
Now, we have to style the hyperlinks. We’ll use a block
display which allows us to specify the width of the links. In
addition, we’ll center align the text and remove all
underlines. We’ll also add a background color to our links.
a {
display: block;
width: 160px;
text-align: center;
text-decoration: none;
background-color: #00FF00;
}
Finally, if we want the navigation bar to be a horizontal bar,
we need to float the list items left. Otherwise, the list items
will be displayed as a vertical bar.
li {
float: left;
}
There you go! We’ve just created a simple horizontal
navigation bar. The source code for this navigation bar is
given as part of the exercise for this chapter. Play around
with it and try to make it more visually appealing. You can
also specify different styles for the four different link states.
list-style-position: outside;
Exercise 9.2
1. Open the file Chapter 9 - Navigation Bar.html
concurrently in your browser and text editor.
table {
border: dashed 1px black;
padding: 50px;
margin: 60px;
}
th {
border: solid 1px black;
padding: 30px;
text-align: center;
}
td {
border: solid 1px black;
padding: 20px;
}
The dotted line is the table’s border. Space surrounding the
dotted border is the table’s margin (declared to be 60px)
and space within the dotted border is its padding (50px).
The first row (Firstname, Lastname, Age) is defined as the
table heading using the <th> tag. Space surrounding the
words ‘Firstname’, ‘Lastname’ and ‘Age’ is the padding for
the <th> element (30px).
The second, third and fourth row is defined using the <td>
tag. Space surrounding words like ‘Derek’, ‘Aaron’ and ‘31’
is the padding for the <td> element (20px).
No margins are declared for the <th> and <td> elements as
margins are ignored for table cells. Hence, we cannot
specify the spacing between the cells. By default, there’ll be
a small gap between individual table cells. In addition,
there’s also a gap between the table’s border (the dotted
line) and the borders of the cells (the solid lines) even if you
set table padding to 0px. If you only want one border, you
have to use the border-collapse property:
border-collapse: collapse;
We’ll have a chance to play around with the border, padding
and margin properties when we do the exercise for this
chapter. For now, let’s move on to the next property.
Height and Width
The width and height of a table can be set using the width
and height properties. The values are normally given in
pixels or as a percentage. For instance, the code below sets
the table width to be 100% of the parent element and the
height to be 500px.
table {
width: 100%;
height: 500px;
}
You can also use the height property at the tr, th or td level.
For instance, if you want the table header row to have a
height of 100px, you can write
th {
height: 100px;
}
In addition, you can set the width property at the table cell
level (i.e. for the td and th elements). If you want the table
cells to have a width of 200px, you can write
th {
width: 200px;
}
If you want to style individual columns, you can use the
id/class attribute to do it. For instance if you have the table
structure below:
<table>
<tr>
<th id=”firstColumn”>First Column</th>
<th id=”secondColumn”>First Column</th>
</tr>
<tr>
<td>Some data</th>
<td>More data</th>
</tr>
</table>
you can set the width of the table columns individually like
this:
#firstColumn {
width: 40%;
}
#secondColumn {
width: 60%;
}
Text Alignment
Text within table cells can be aligned horizontally using the
text-align property and vertically using the vertical-align
property. The commonly used values for the text-align
property are center, left, right and justify. The commonly
used values for the vertical-align property are top, middle
and bottom.
Examples:
th {
text-align: center;
vertical-align: middle;
}
Background, Font and Text
Tables can also be styled using properties for background,
font and text covered in Chapter 7 and 8. For instance, the
code below will set the text color of <th> elements to white
and give the elements a green background color.
th {
background-color: green;
color: white;
}
nth-child( ) Selector
Sometimes when we have a very large table with a lot of
rows, the table may be difficult to read.
One way to improve the readability of large tables is to color
alternating rows. This can be easily achieved with the nth-
child( ) selector.
To color even rows, we write
tr:nth-child(even) {
background-color: lightgreen;
}
To color odd rows, we write
tr:nth-child(odd) {
background-color: lightgray;
}
Exercise 10
Download the source code for this exercise from
http://learncodingfast.com/css and unzip the file. The source
code for this exercise can be found in the Chapter 10 -
Tables folder.
Exercise 10.1
1. Open the file Chapter 10 - Tables.html concurrently in
your browser and text editor.
#firstColumn {
width: 100px;
}
#secondColumn {
width: 200px;
}
#thirdColumn {
width: 50px;
}
tr:nth-child(even) {
background-color: lightgreen;
}
tr:nth-child(odd) {
background-color: lightgray;
}
Bonus Project
Congratulations! We’ve now covered enough fundamentals
of CSS (and HTML) to start coding our first webpage from
scratch. The best way to learn CSS is by doing. Hence, I’ve
included a bonus project with this book where you’ll be
guided through the coding of a webpage for a fictitious
travel agency. You can check out the demo for the project at
http://www.learncodingfast.com/demo/jetspeed.html.
Initially I intended to include the project at the end of the
book. However, given the graphical nature of CSS, I decided
that including all the instructions and images for the project
in a kindle book is not ideal. Therefore, I created a separate
PDF file for the project that you can download at
http://learncodingfast.com/css.
I strongly encourage you to try the project as it’ll give you a
chance to see how all the concepts that you’ve learnt in this
book tie together. Working through the project will help
solidify your learning and fill all the gaps that you may have.
Have fun coding!
Thank You
We’ve come to the end of the book. Thank you for reading
this book and I hope you have enjoyed the book. More
importantly, I sincerely hope the book has helped you
master the fundamentals of CSS.
I know you could have picked from a dozen of books on CSS,
but you took a chance with this book. Thank you once again
for downloading this book and reading all the way to the
end. Please try the exercises and the bonus project. You’ll
learn a lot by doing.
Now I’d like to ask for a “small” favor. Could you please take
a minute or two to leave a review for this book on Amazon?
This feedback will help me tremendously and will help me
continue to write more guides on programming. If you like
the book or have any suggestions for improvement, please
let me know. I will be deeply grateful. :) Last but not least,
remember you can download the source code for the project
and the exercises at http://www.learncodingfast.com/css.
You can also contact me at [email protected].
Appendix A: Source Code for
Exercises
Exercise 3.1
<!doctype html>
<html>
<head><title>Chapter 3 - Basics of CSS</title> <style>
p{
background-color: yellow; }
</style>
</head>
<body>
<h1>Chapter 3 - Basics of CSS</h1> <h2>CSS
Selectors</h2>
<p>This exercise uses background color to help us figure
out which element we are selecting. This paragraph has no
class or id.</p>
<p id = "myIDPara">This paragraph has id = "myIDPara".
</p>
<p class = "myClassPara">This paragraph has class =
"myClassPara".</p>
<p class = "myClassPara mySecondClassPara">This
paragraph has class = "myClassPara" and class =
"mySecondClassPara".</p>
<div>
This is some text in the div element.
<p>This paragraph is the first child element of the 'div'
element.</p> <p>This paragraph is the second child
element of the 'div' element.</p> <p>This paragraph is the
third child element of the 'div' element.</p> </div>