0% found this document useful (0 votes)
104 views36 pages

Web1201 Lab2 Css

This document provides an introduction to CSS and its core concepts. It discusses: 1. CSS allows modification of color and text on a webpage. It overrides browser default styles with increasing specificity of user styles, author styles, and !important declarations. 2. Key CSS concepts are cascading (order of declarations), specificity (how specific a declaration is), and inheritance (what styles a child element inherits). 3. There are different ways to apply CSS including embedded, external, and inline. The order CSS is applied is browser defaults, user styles, author styles, with !important overriding normal declarations.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views36 pages

Web1201 Lab2 Css

This document provides an introduction to CSS and its core concepts. It discusses: 1. CSS allows modification of color and text on a webpage. It overrides browser default styles with increasing specificity of user styles, author styles, and !important declarations. 2. Key CSS concepts are cascading (order of declarations), specificity (how specific a declaration is), and inheritance (what styles a child element inherits). 3. There are different ways to apply CSS including embedded, external, and inline. The order CSS is applied is browser defaults, user styles, author styles, with !important overriding normal declarations.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Rev 2.

1
August, 2020

Lab 2: CSS
WEB1201: Web Fundamentals

1 Introduction
This lab is intended to get you accustomed to CSS to modify the colour and text of your website
from Lab 1. It is expected that you have completed Lab 1 and is well versed with HTML and
the different terms associated with HTML.

2 Objectives
At the end of this lab, you should be able to:

1. Modify the colour and text of a web page using CSS.


2. Describe what CSS is and how it can be used to modify the colour and text of a web page.

3 Deliverables, timing and additional notes


The estimated time of completion for this lab is approximately two (2) hours (assuming you
have gone through the theory). This does not include the time you will need to answer the
questions. You are to compile your work after every lab - this includes all codes (and com-
ments where necessary), documentation, completed tasks and answered questions. You have to
submit your work at the end of this lab.

4 Materials and Equipment


1. A computer with a web browser.
2. A text editor (Notepad, Notepad++, Sublime, Vi, Vim, etc.). It is highly recommended
that you use a text editor that support syntax highlighting as it will make it easier to work.
3. Files from “Lab 1 - HTML”.

Note

You should have a logbook as a place to write down notes for labs. This will help you revise
and reflect on the work you have done in the lab.

1
5 Introduction to the lab
In this lab we will be looking at Cascading Style Sheets (CSS) that will help us style different
parts of our web page. Figure 1 shows how the lab will be broken down and how the theory will
be presented within the lab sheet.

1 CSS
What is it?

2 CSS Specification 3 CSS Selector 4 CSS Declarations


Where and how to What does it apply to? What can change?
specify?
Scope

Universal Selector Global Colour


Embedded Selects all elements
(All)
(background,
(in <style> within (use *) text)
the <head>)

Type Selector Text


All instances of a specific Specific (type, style,
External
HTML element Group size)
(linked to an
(specify that element)
external CSS file)

Class Selector
All instances of an HTML
Imported Specific
element belonging to a Group
(imported using specific class
@import) (specify that class)

ID Selector
Specific
Single instances of an Element
HTML element
(specify that id)

Attribute Selector
All elements that have a Specific
Group
given attribute
(specify that element
with the attribute)

Inline Automatically applied to


Specific
(using the style that specific element the Element
attribute) attribute is in

Figure 1: CSS overview

2
6 What is CSS?
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation
of a document written in a markup language like HTML. There are a few key concepts in
understanding how CSS works:

• Cascade: the order of the CSS declaration

• Specificity: how specific is the CSS declaration

• Inheritance: what was the CSS of the parent element and what does the child element
inherit?

Understanding these concepts will help you:

• control how CSS is applied to HTML

• how conflicts (in the CSS declarations) are resolved

6.1 What does “cascading” mean?

“Cascading” means that styles can fall (or cascade) from one style sheet to another, enabling
multiple style sheets to be used on one HTML document. This means that that order of the CSS
rules matter!

A HTML document may have three or more style sheets associated with it including (in in-
creasing priority):

1. The user agent1 (typically a web browser) style sheet


2. The user style sheet
3. The author style sheet

6.1.1 User agent style sheets

A user agent is any software that retrieves and presents Web content for end users or is im-
plemented using Web technologies that help in retrieving, rendering and interacting with Web
content. In most cases, your user agent will typically be the web browser. The browser will
apply style sheets to all web documents. Although these style sheets vary from browser to
browser, they all have common characteristics such as black text, blue links, purple visited links
etc. These are referred to as a “default” browser stylesheet.

As soon as you, the author, apply a style sheet to a document, it will override the browser’s style
sheet. This is because author style sheets will always override browser style sheets.
1
We will use the term user agent and web browser interchangeably since the web browser is most likely the
user agent you will be using.

3
6.1.2 User style sheets

A user is anyone who looks at your website. Most modern browsers allow users to set their own
style sheets within their browser. These style sheets will override the browsers default style
sheets - for that user only.

6.1.3 Author style sheets

The author is the person who develops the website and in this subject, that will be you!

As soon as you apply a basic style sheet or an inline style to a page, you have added what is
referred to as an “author style sheet”. Everything you do, from choosing fonts, colours and
laying out pages in CSS is done using author style sheets.

Author style sheets can be applied inside an HTML document or by linking to an external
file. You can also use multiple style sheets on an particular document to take advantage of the
cascade.

6.2 So which style sheets applies?

With the different style sheets, CSS declarations are applied in this order (from lowest to highest
priority):

1. user agent (the browser)


2. user normal
3. author normal
4. author important2
5. user important

Without the use of the !important declaration author→user→ browser styles.

6.2.1 Using !important

If you are reading this lab sheet in sequence, we have yet to introduce how to declare CSS.
Therefore, come back to this example after you have gone through the rest of the lab sheet.
1 p{
2 color: red !important; // Just add the !important at the end of EACH line.
3 background-color: blue !important; // Like this
4 }
5 #greenPara {
2
You can set “!important” on any declaration and this will override other declarations for the same element.
!important declarations override normal declarations.

4
6 color: green; // This should make the paragraph green (if the !important) was
removed from the CSS declaration.
7 }
8
9 // In the document
10 <p id="greenPara">Will be RED (rather than GREEN).</p> // The !important
declaration overrides the #greenPara declaration

Notes:

• !important needs to be added to each declared CSS property. Notice that it comes BE-
FORE the semi-colon (;), thus, it belongs to that property.

• Based on SPECIFICITY, the paragraph (with the id attribute) should be green but the
!important overrides this behaviour.

Note

In this lab, you are considered the author of the web page, therefore, the CSS that you
declare and apply will be the “author normal”.

Task 1: Testing the source order


Note: Although this task is placed here, come back to this task after you have completed read-
ing through the theory and the other tasks. So what happens when you have multiple CSS
declarations for the same HTML element? This is what we will be exploring in this task.

1. Using the embedded CSS method, declare two CSS declarations for the same selected
element, e.g. two declarations for h1, two declarations for span, etc.
2. The two declarations MUST have the same declaration property but with different decla-
ration values.
Note: You will need to be able to write code based on a given instruction. This is practice
for that.
3. In the HTML document, declare the element that was selected.
4. Record your observation, discussion and conclusion from this.
5. Submit your file as: conflict_test.html

See clue(s)

5
Question(s) 1

1. Explain what are the potential uses for a cascading style sheet rather than a
non-cascading one.

6.3 Specificity

Specificity is how the browser decides which rule applies if multiple rules have different se-
lectors, but could still apply to the same element. It is basically a measure of how specific a
selector’s selection will be:

• An element selector is less specific — it will select all elements of that type that appear
on a page — so will get a lower score.

• A class selector is more specific — it will select only the elements on a page that have a
specific class attribute value — so will get a higher score.

Here is an example:
1 // In the <style>
2 .headingClass {color: red;} // First declaration
3 h1 {color: blue;} // Second declaration
4
5 // In the document:
6 <h1 class="headingClass">I will be RED.</h1>

6.4 Inheritance

Some CSS property values set on parent elements are inherited by their child elements, and
some are not.

Here is an example:
1 // In the <style>
2 p {color: red;} // Declaring a parent style
3
4 // In the document:

6
5 <p>This is the parent which is RED and any child like <span>this will also be
RED</span> because the child has inherited the color of the parent.</p> //
Here, <span> has inherited the colour of <p>

Task 2: Testing inheritance


Note: Although this task is placed here, come back to this task after you have completed reading
through the theory and the other tasks.

1. Modify the example and add another declaration for the <span> element. In this decla-
ration, define a new colour for <span>.
2. Record your observation, discussion and conclusion from this.
3. Submit your file as: inheritance_test.html

Note: A list of inherited properties have been omitted and left to you to find out. You will find a
question on this at the end of the lab sheet.

6.5 Summary: So...which styles apply to an element?

When a web browser tries to determine which style(s) to apply to an element, there are three
factors to consider, listed here from the highest importance to the least, i.e. the earlier listed
rules will overrule later ones:

1. Importance
2. Specificity
3. Source order

Also, keep in mind what CSS properties are inherited and what are not.

7
7 Ways of inserting style sheets
How and where will you specify the styles that you want to apply? There are four ways of
inserting style sheets:

1. Embedded:
(a) where: specified within a HTML <style> element located in the head section of
the HTML document
(b) applies to: elements in the entire web page (i.e. the whole HTML document)
Specific or groups of elements can be styled using:
i. class
ii. id
iii. CSS selectors
2. Inline:
(a) where: specified using the style attribute the body section of the HTML document
(b) applies to: that specific element where the style is specified
3. External:
(a) found in: separate file (typically saved with .css file extension)
The file is then associated with the HTML using a HTML link element in the head
section of the file
1 <head>
2 <link rel="stylesheet" type="text/css" href="mystyle.css">
3 </head>

(b) applies to: any web page linked to the style sheet file
This allows you to have a consistent look and feel across multiple web pages.
4. Imported:
Note: This is very simialr to “external” as both do not have styles specified within the
same HTML document.
(a) found in: another web site, your site in another location, etc. (anywhere a URL can
locate)
(b) uses @import to import another CSS file. Can be used in-lieu of <link> in some
applications. For example to import the same “mystyle.css” file, you can use import.
1 <head>
2 @import url(’mystyle.css’);
3 </head>

More instructions found here @import page at mozilla.org

8
Question(s) 2

1. (Challenge) Explain when and why the imported method will be used over
external method and vice-versa? In your explanation, include any technical
information that would influence the choice made.

Note: This question requires you to explore further and read about things that
are not directly related to this subject but is invaluable when you want to better
understand the underlying principles and how it affects computing processes
in general. For computing students, you will find that this is related to other
subjects you will be learning later on. I will urge you to try to understand the
concepts presented when you explore or investigate this question.

8 CSS Selectors and Declarations


Style sheets are composed of style rules that describe the styling to be applied. Each rule has
two parts: a selector and a declaration:

1. CSS Style Rule Selector The selector can be an HTML element name, a class name or
an id name3 .
2. CSS Style Rule Declaration The declaration indicates the CSS property you are setting
(such as color) and the value you are assigning to the property.

For example, the CSS rule shown in Figure 2 below would set the color of the text used on a
web page to blue. The selector is the body tag and the declaration sets the color property to the
value of blue.

Figure 2: Examples of a CSS selector and declaration.

You can have multiple declarations within the same selector or when using the style attribute,
separated by a semicolon. Here are some examples:

3
If using the inline method of declaration, CSS selectors do not apply as what the CSS applies to is implicit,
i.e. CSS for that element itself

9
1 // Single property; embedded, external, imported declaration method
2 body{color:blue}
3 // Two properties, separated by a semicolon (in red)
4 body{color:blue; background-color:red}
5 // Two properties; inline declaration method
6 body<style="color:blue; background-color:red">

Note

The method of commenting in these examples is NOT HTML and only used here for ex-
planation purposes. Do NOT use it in your own HTML codes.

8.1 CSS Selectors (Basic selectors)

CSS can be applied to every element on a web page/site or to a specific element. (Read more
here). Let’s look at some examples of how you can apply CSS to different scopes of elements:

1. Universal selector
Selects all elements (i.e. matches all the elements of the document).
Method 1: Embedded declaration method
1 <head>
2 <style>
3 *{color:red} // Makes all elements have a red text
4 </style>
5 </head>

Method 2: External/imported declaration method


In a .css file (e.g. with a filename mycss.css)
1 *{color:red}
2 /* Note: Only the CSS declarations are in the file. No HTML elements or
tags.*/

In the HTML file that is going to include this CSS


1 <head>
2 <link rel="stylesheet" type="text/css" href="mycss.css">
3 </head>

Notes:
• Both Method 1 and Method 2 achieve the same results using different ways to de-
clare.

10
• For Method 2, it is assumed that the CSS file and the HTML file are located in the
same folder or directory. If this is not the case, please refer to the difference between
relative and absolute links and how they are used on a local machine.
2. Type selector
All elements of a particular name.
1 // Declare the element name that you want to style.
2 <head>
3 <style>
4 h1{color:red} // Makes all <h1> elements have red text
5 p{color:red} // Makes all <p> elements have red text
6 </style>
7 </head>

Notes:
• Element names are declared within the <style> element.
• CSS declarations will affect all elements with that name.
3. Class selector
Selects all elements that have the given class attribute.
1 // Declare the class name that you want to style.
2 <head>
3 <style>
4 .aClassName{color:red}
5 </style>
6 </head>
7
8 // Within the document:
9 <p class="aClassName">This text is red</p> // class attribute declared as
‘‘aClassName’’ to match the CSS declaration.
10 <p>This text is NOT red</p>
11 <p class="aClassName">This text is also red</p> // 2nd use.
12 <div class="aClassName">This text is also red</div> // 3rd use.

Notes:
• Class names are declared within the <style> element and is preceded with a period.
• This is not so much CSS related but more HTML. Remember that multiple elements
can belong to the same class. What this means is you can declare different or multi-
ple elements to have the same class name. Compare this to using the id attribute.
4. ID selector
Selects all elements that have the given ID attribute.
1 // Declare the ID that you want to style.
2 <head>

11
3 <style>
4 #aClassName{color:red}
5 </style>
6 </head>
7
8 // Within the document:
9 <p id="aClassName">This text is red</p> // ID attribute used.
10 <p>This text is NOT red</p>
11 <p id="aClassName">What colour is this text?</p> // invalid.

Notes:
• ID names are declared within the <style> element and is preceded with a hash.
• This is not so much CSS related but more HTML. Remember that each ID can only
be used for ONE element in a document. This means you cannot declare multiple
elements to “share” a single ID.
5. Attribute selector
Selects all elements that have the given attribute.
1 <head>
2 <style>
3 div[title]{color:red} // Apply to all <div> with a title attribute
4 div[chp]{color:green} // Apply to all <div> with a chp attribute
5 </style>
6 </head>
7
8 // Within the document:
9 <div title="chapter1">This text is red</div> // title attribute used.
10 <div title="chapter2">This text is red</div> // title attribute used.
11 <div title="section1">This text is red</div> // title attribute used.
12 <div title="">This text is red</div> // title attribute used.
13 <div chp="">This text is green</div> // chp attribute used.
14 <div note="another">This text is NOT red</div> // NO title attribute.
15 <div>This text is NOT red</div> // No attribute.

Notes:
• Similar to using the Type selector but with an appended attribute name in the square
brackets.
• The value of the attribute (i.e. the contents within the quotation marks) do not matter.
The style is applied if the attribute exists.
• This is not so much CSS related but more HTML. Multiple elements can have the
same attribute.

12
8.2 CSS Selectors (Group selectors)

Instead of declaring multiple elements that have the same style individually, you can group
them. Example:
1 // From an earlier example:
2 <head>
3 <style>
4 p{color:red}
5 div{color:red}
6 .aClass{color:red}
7 #anID{color:red}
8 </style>
9 </head>

Rather than having multiple CSS declarations, we can group them:


1 // Grouping (on one line):
2 <head>
3 <style>
4 p,div,.aClass,#anID{color:red}
5 </style>
6 </head>

For readability, we can put the different declarations on separate lines:


1 // Grouping (on separate lines):
2 <head>
3 <style>
4 p,
5 div,
6 .aClass,
7 #anID {
8 color:red;
9 }
10 </style>
11 </head>

Notes:

• Multiple element names can have the same CSS declaration.

• Not all CSS declarations can be grouped (e.g. declarations for pseudo classes and ele-
ments)

13
8.3 CSS Selectors (Combinators)

Combinators allow us to select specific elements or groups of elements based on their relation-
shio to OTHER elements. To better understand what combinators are, here is a list with a brief
description:

1. Descendant combinator
The (space) combinator selects nodes that are descendants of the first element (regard-
less of how deep it is nested or if it is nested inside another element).
2. Child combinator
The > combinator selects nodes that are direct children of the first element. Think of this
as a “stricter” version of the descendant combinator.
3. General sibling combinator
The ~ combinator selects siblings. This means that the second element follows the first
(though not necessarily immediately), and both share the same parent.
4. Adjacent sibling combinator
The + combinator selects adjacent siblings. This means that the second element directly
follows the first, and both share the same parent.

Examples:

1. Descendant combinator
1 // Descendant combinator declaration:
2 <head>
3 <style>
4 div p {color:red} // match all <p> elements that are inside a
<div> element
5 </style>
6 </head>
7
8 // In the body:
9 <div>
10 <p>Red text 1 // <p> within <div>
11 <p>Still red text 1.1</p> // <p> still within <div>
12 </p>
13 <p>Red text 2</p>
14 <span>This text will not be red
15 <p>But this text will be red</p>
16 </span>
17 </div>
18 <p>Not red text</p> // This <p> is not inside <div>

14
Notes:
• In this example, the style will apply to any <p> that is within the <div>...</div>
(From Line 9 to Line 17).
2. Child combinator
1 // Child combinator declaration:
2 <head>
3 <style>
4 div > p {color:red} // match all <p> elements that is a child of a
<div> element
5 </style>
6 </head>
7
8 // In the body:
9 <div>
10 <p>Red text 1 // <p> within <div>. This paragraph will be RED
including all children.
11 <p>Red text 1.1</p> // <p> is not a child of <div> but
another <p> which a style which can be inherited was
applied to. Therefore the style for this <p> is inherited
from the parent <p>.
12 </p>
13 <p>Red text 2</p> // Another <p> within <div>
14 <span>This text will not be red</span>
15 </div>
16 <p>Not red text</p> // This <p> is not inside <div>

3. General Sibling Combinator


1 // General sibling combinator declaration:
2 <head>
3 <style>
4 p ~ span {color:red} // spans that are siblings of paragraphs
5 </style>
6 </head>
7
8 // In the body:
9 <span>Not RED</span>
10 <p>Also not RED</p>
11 <span>RED</span>
12 <div>Not RED</div>
13 <span>RED</span> // Take note of this line. This will change later.
14 <p>Not red text</p>

15
4. Adjacent Sibling Combinator Similar to the general sibling combinator but the second
element is only styled if it immediately follows the first element.
1 // Adjacent sibling combinator declaration:
2 <head>
3 <style>
4 p + span {color:red} // spans that are siblings of paragraphs
5 </style>
6 </head>
7
8 // In the body:
9 <span>Not RED</span>
10 <p>Also not RED</p>
11 <span>RED</span>
12 <div>Not RED</div>
13 <span>Not RED</span> // This does span does NOT immediately follow
a paragraph
14 <p>Not red text</p>

Question(s) 3

1. Describe all the CSS basic selectors.


2. Describe how to group CSS declarations for different elements.

16
9 CSS Declaration: Specifying colour in CSS
There are several ways to specify colours in CSS.

1. Hexadecimal colors
2. RGB colours
3. RGBA colours
4. HSL colours
5. HSLA colours
6. Predefined/Cross-browser colour names

Here are some examples:

CSS Syntax Colour Type

p{color: red;} Using the colour name.


p{color: #FF0000;} Hexadecimal colour value. Two hex values for
each colour component
p{color: #F00;} Shortened or shorthand hexadecimal. One hex
value for each hex pair for use only with web-
safe colours that have repeated hex pair values.
p{color: rgb(255,0,0);} Decimal colour values (using RGB triplet val-
ues)
p{color: hsl(0,100%,50%);} Hue Saturation Lightness value

You can find more information in this link.

9.1 Hexadecimal color values

1. Hexadecimal is the name for the base-16 numbering system, which uses the characters
0,1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F to specify numeric values.
2. The number represents a 24-bit value for colour (8-bits for each red, green and blue
primary additive colours), broken down as #RRGGBB.
3. Begins with a # followed by 6 hex digits ranging from 00 to FF (0 to 255 in base 10)
4. The # symbol signifies that the value is hexadecimal. You can use either uppercase or
lowercase letters in hexadecimal color values; #FF0000 and #ff0000 both configure
the color red.

9.2 RGB(A) Colours

1. Specifies the intensity of each of the red, green and blue colour components.
2. It is specified in decimal values from 0 to 255, representing an 8-bit value with 256

17
different intensity values. 0→no intensity, 255→maximum intensity.
3. The RGBA version has an additional Alpha (A) channel with values that range from 0.0
to 1.0 that allows you to control the opacity of the colour. 0→fully transparent, 1→fully
opaque. This is probably most noticeable when the Alpha channel is applied to a fore-
ground object that will allow the background object to be partially seen.

9.3 HSL(A) Colours

1. Specifies the colour using the hue, saturation and lightness.


(a) Hue:
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue.
See Figure 3 for the HSL colour wheel to refer to the Hue colours.
(b) Saturation:
Saturation is a percentage value; 0% means a shade of gray and 100% is the full
color.
(c) Lightness:
Lightness is also a percentage; 0% is black, 100% is white.
2. The HSLA version has an additional Alpha (A) channel with values that range from 0.0
to 1.0 that allows you to control the opacity of the colour. 0→fully transparent, 1→fully
opaque.

Figure 3: HSL colour wheel (from https://tympanus.net/codrops/css_reference/hsl/

18
9.4 Colour Names

1. You use one of the 140 predefined colour names.


2. The names are NOT case sensitive, i.e. “red” is the same as “RED”.

Key Word Hexadecimal RGB Key Word Hexadecimal RGB

Red #FF0000 (255,0,0) Navy #000080 (0,0,128)


Yellow #FFFF00 (255,255,0) Purple #800080 (128,0,128)
Lime #00FF00 (0,255,0) Fuchsia #FF00FF (255,0,255)
Green #008000 (0,128,0) Maroon #800000 (128,0,0)
Olive #808000 (128,128,0) Black #000000 (0,0,0)
Teal #008080 (0,128,128) Gray #808080 (128,128,128)
Aqua #00FFFF (0,255,255) Silver #C0C0C0 (192,192,192)
Blue #0000FF (0,0,255) White #FFFFFF (255,255,255)

Task 3: Using Inline CSS


In this task, we are going to specify a global body tag style by using the inline declaration
method: off-white background with teal text. These styles (the color and background-color)
will be inherited by other elements by default. For example (shown without the closing tag):
1 <body style="background-color:#F5F5F5;
2 color:#008080;">
3 </body>

Let us examine the code:

• Style is a HTML attribute (refer to previous labs of on what a HTML attribute is).

• As with all HTML attributes, the values associated with the attributes appear AFTER the
equal sign.

• All CSS declarations are declared within quotation marks.

• Multiple CSS declarations can be made (like embedded) but separated using semicolons.

For this lab, we will define two colours:

• off-white: #008080
• teal: #F5F5F5

Use the colours specified to create the web page as shown in Figure 4.

1. Modify the title element to:


Inline CSS example

19
2. In the body element, set body to have a teal background and off-white words.
3. Create a level 1 heading with the words:
Inline CSS
4. Set h1 to have a off-white background and teal words.
5. Create a paragraph and Write the following in that paragraph:
This paragraph inherits the styles applied to the body tag
6. Test your web page. It should look like Figure 4

Figure 4: Example of inline CSS for styling the body and h1.

7. Now add another paragraph and write the following in that paragraph:
This paragraph overrides the text colour applied to the body tag.
8. Style just this paragraph (i.e. the 2nd paragraph) to have text with the colour #333333.
9. Test your web page. It should look like Figure 5

Figure 5: Second example of inline CSS for styling the body and h1

10. Save your final file as styled_inline_CSS.html. You have to submit this file.

Question(s) 4

1. State another method for how the colour #333333 can be declared?

20
Your final code should look like the following: Show answer

Task 4: Using Embedded CSS


In the previous task, you added inline styles for one of the paragraphs. To do so, you coded a
style attribute on the paragraph element. But what if you needed to configure the styles for 10
or 20 paragraphs instead of just one? Using inline styles, you might be doing a lot of repetitive
coding! While inline styles apply to one HTML element, embedded styles apply to an entire
web page.

• Embedded styles are placed within a <style> element located in the head section of a
web page.

• The opening <style> tag and the closing </style> tag contain the list of embedded-
style rules.

Use these colours as a reference.

• Dark purple: #191970

• Purple: #AEAED4

• Light purple: #E6E6FA

1. Using your files from Lab1, modify the home page (index.html) to look like Figure 6.
You will need to add additional HTML elements.
2. You are going to style the body, h1 and h2 to the following:

21
Figure 6: Unstyled web page from the previous lab.

• body:
background colour: light purple, colour: dark purple
• h1:
background colour: dark purple, colour: light purple
• h2:
background colour: purple, colour: dark purple
This is a monochromatic colour scheme. To help you with the coding, here is a snippet of
only part of the codes shown here for the <body>. You will have to do the rest for h1
and h2.
1 <style>
2 body{background-color: #e6e6fa; color: #191970}
3 </style>

3. After you have added the rest of the styling lines, your web page should look like Figure 7.
4. Save your file as: styled_embedded_CSS.html. Include this in your submission.

What have you learnt from this exercise?

1. All the styles were in a single place on the web page. Since embedded styles are coded in
a specific location, they are easier to maintain over time than inline styles.

22
Figure 7: Styled web page after applying the CSS.

2. Notice that you coded the styles for the h2 element selector only once (in the head section)
and both <h2> elements applied the h2 style. This approach is more efficient than coding
the same inline style on each <h2> element.

Further tasks:

These are additional tasks for you to explore.

1. Try using HSL to create (approximately) the same look.


Hint: It is best to first determine the three (3) HSL values that you will be using before
starting just as we did with the hex colour values earlier.
2. Try making the background of h1 and h2 semi-transparent by setting the opacity value.
3. Save your file as: styled_embedded_CSS_hsl.html. Include this in your submission.

10 Configuring Text with CSS


In this section, you will learn to use CSS to configure font typeface. Using CSS to configure
text is more flexible (especially when using an external style sheet, as you will discover later in
the chapter) than using HTML elements and is the method preferred by modern web developers

23
10.1 font-family Property

The font-family property configures font typeface. A web browser displays text using the fonts
that have been installed on the user’s computer. When a font is specified that is not installed on
your web visitor’s computer, the default font is substituted. Times New Roman is the default
font displayed by most web browsers. Table 1 shows font family categories.

Table 1: Common font families

Font family Font family description


category
serif Serif fonts have small embellishments (or serifs) on the end of letter strokes;
often used for headings.
sans-serif Sans comes from the latin word “sine” to mean “without”. Sans-serif fonts
are fonts without the serifs; often used for web page text.
monospace Fixed-width font; often used for code samples.
cursive Hand-written style; use with caution as it may be difficult to read on a web
page.
fantasy Exaggerated style; sometimes used for heading but use with caution as it may
be difficult to read on a web page.

10.2 font-size property

The font-size property sets the size of the font. Table 7 lists a wide variety of text and numeric
values—there are almost too many choices available. See the notes in Figure 7 for recom-
mended use

Notes about the em and percentage values

The em unit is a relative font unit that has its roots in the print industry, dating back to the day
when printers set type manually with blocks of characters. An em unit is the width of a square
block of type (typically the uppercase M) for a font and type size. On web pages, an em unit
corresponds to the width of the font and size used in the parent element (typically the body
element). So, the size of an em unit is relative to the font typeface and default size. Percentage
values work in a similar manner to em units. For example, font size: 100% and font-size: 1em
should render the same in a browser.

10.3 text-shadow property

The CSS text-shadow property adds depth and dimension to text displayed on web pages. Cur-
rent versions of modern browsers, including Internet Explorer (version 10 and later) support the
text-shadow property. Configure a text shadow by coding values for the shadow’s horizontal
offset, vertical offset, blur radius (optional), and colour:

24
Table 2: Different options for configuring font size using CSS

Value category Values Notes


Text Value xx-small, x-small, Scales well when text is resized in browser;
small, medium limited options for text size.
(default), large, x-large,
xx-large
Pixel Unit (px) Numeric value with Pixel-perfect display depends on screen res-
unit, e.g. 10px olution; may not scale in every browser when
text is resized.
Point Unit (pt) Numeric value with Use to configure print version of web page;
unit, e.g. 10pt may not scale in every browser when text is
resized.
Em Unit (em) Numeric value with Recommended by W3C; scales will when
unit; e.g. 0.75em text is resized in browser; many options for
text size.
Percentage Numeric value with Recommended by W3C; scales will when
percentage; e.g. 75% text is resized in browser; many options for
text size.

1. Horizontal offset.
Use a numeric pixel value. Positive value configures a shadow on the right. Negative
value configures a shadow on the left.
2. Vertical offset.
Use a numeric pixel value. Positive value configures a shadow below. Negative value
configures a shadow above.
3. Blur radius (optional).
Configure a numeric pixel value. If omitted, defaults to the value 0 which configures a
sharp shadow. Higher values configure more blur.
4. Color value. Configure a valid color value for the shadow.

Task 5: Changing the font styles


1. Using your file “styled_embedded_CSS.html”, modify it to add in the last line of the style
element.
1 <style>
2 body{ background-color: #e6e6fa;
3 color: #191970;
4 font-family: Arial, Verdana, sans-serif;}
5 </style>

The new font typeface style rule shown in the following code will apply to the entire web
page unless more specific style rules are applied to a selector (such as h1 or p), a class, or

25
an id (more on classes and ids later).
2. Configure the h1 selector: (Use the embedded declaration method)
• Set the line-height property: 200%
• Set h1 to use a serif font. (Hint: use Georgia, Times New Roman and end with the
general font family category)
• Add a shadow with a gray (#CCCCCC) text shadow with a 3 pixel vertical and
horizontal offset and a blur radius of 5 pixels.
• Add a nonbreaking space special character in the body of the web page after the
opening <h1> tag.
3. Configure the h2 selector: (Use the embedded declaration method)
• Set the typeface to the same as h1.
• Center the text. (Hint: text-align)
4. Configure the Paragraphs: (Use the embedded declaration method)
• Text slightly smaller than the default text size: 0.90em
• Configure the first line of each paragraph to be indented: 3em (Hint: text-indent)
5. Configure the unordered list by making the text bold. (Hint: Use an inline style and
font-weight)
6. After you have added the rest of the styling lines, your web page should look like Figure 8.
7. Save your file as styled_embedded_CSS_fonts.html. Include this in your submis-
sion.

26
Figure 8: Styled web page after applying the CSS font properties.

11 Recap: Class, id and Descendant selectors

11.1 Class selector

Use a CSS class selector when you need to apply a CSS declaration to certain elements on a
web page and not necessarily tie the style to a particular HTML element. When setting a style
for a class, configure the class name as the selector. Place a dot, or period (.), in front of the
class name in the stylesheet. The following code configures a class called “feature” (you can
use any name) in a style sheet with a foreground (text) color set to a medium red and is added
to the <style> element.
1 .feature{color:#C70000;}

The styles set in the new class can be applied to any element you wish. You do this by using
the class attribute, such as class=“feature”. Do not type the dot in front of the class value in the
opening tag where the class is being applied. The following code will apply the feature class
styles to a <li> element:
1 <li class="feature">Usability Studies</li>

27
2 <li class="feature">Search Engine Optimization</li>

11.2 id Selector

Use a CSS id selector to identify and apply a CSS rule uniquely to a single area on a web page.
Unlike a class selector which can be applied multiple times on a web page, an id may only be
applied once per web page. When setting a style for an id, place a hash mark (#) in front of the
id name in the style sheet. An id name may contain letters, numbers, hyphens, and underscores.
id names may not contain spaces. The following code will configure an id called “main” in a
style sheet:
1 #main{color:#333333;}

The styles set in the main id can be applied to any element you wish by using the id attribute,
id=“main”. Do not type the # in front of the id value in the opening tag. The following code
will apply the main id styles to a div tag:
1 <div id="main">This sentence will be displayed using styles configured in the
main id.
2 </div>

11.3 Descendant Selector

Use a CSS descendant selector when you want to specify an element within the context of its
container (parent) element. Using descendant selectors can help you to reduce the number of
different classes and ids but still allows you to configure CSS for specific areas on the web page.

For example, if you want to change the colour of all <p> elements, that are descendants of
<div> elements, to “red”.
1 div p {color:red;}

The descendant selector is one type of CSS combinator. A combinator is something that ex-
plains the relationship between the selectors. A CSS selector can contain more than one simple
selector. Between the simple selectors, we can include a combinator. There are four different
combinators in CSS:

1. descendant selector ( ) (yes, a blank space)


2. child selector (>)
3. adjacent sibling selector (+)
4. general sibling selector (~)

You are encouraged to read about the other combinators and how you can use them.

28
Task 6: Changing styles using classes
You will modify the CSS and the HTML in the Trillium Technologies page to configure the
navigation and page footer areas

Steps:

1. For this task you will be using your file “styled_embedded_CSS_font.html”.


In your style section, you are going to create a few classes to define styles.
2. Configure Nav Area:
• Create a class called “nav” inside the style section.
• To make the navigation links more prominent, we are going to display it in a larger
(1.25em) and bold font.
• Apply this style to the nav element.
3. Configure the Content Area:
• Create a class named “feature” to display text colour as a medium dark red (#C70000).
• Add this style to the last two items of the unordered list
4. Configure the Footer Area:
• Create a class “footer” and apply it to the footer area.
• Set the following properties: font colour: #333333, font size: 0.75em, font-style:
italic
• Apply this style to your footer.
5. Your web page should look like Figure 9.
6. Save your file as “embedded_CSS_class.html”.
7. Try applying two classes to one element. Record your observation in a text file called
“<studentID>_observations.txt” where <studentID> is your Student ID. This is one of
the files you will be submitting later on.

Note

Each task of your observation file should contain the following:

1. title of the task (just give it a short identifiable name)


2. what you did
3. what you observed
4. explain your observation
5. conclusion

29
What happens when you want to change just part of a text rather than the whole HTML element?
We can use the <span> tags and enclose the part of the text in this element when we want to
style it. We are going to try to do this by styling our company name.

1. Create a new CSS class called “company” with the following properties:
(a) font weight: bold
(b) font family: Georgia, Times New Roman, serif
(c) font size: 1.25em
2. Apply this to just the company name. You can do this by doing:
1 <p><span class="company">Trillium Media Design</span> will bring....

3. Check if your company name appears different from the rest of the text.
4. Now change the company name to always appear as red.
5. Save your file as “embedded_CSS_span.html”. Include this in your submission.

Figure 9: Styled web page using classes.

30
Task 7: Changing styles using id
In this task, you will use the id to apply styles to specific elements.

Steps:

1. Using id, change each colour of the first three items of the unordered list
2. Try using the same id in two different elements. Record your observation in your earlier
observation text file.
3. Save your file as “embedded_CSS_id.html”. Include this in your submission.

Additional tasks
In this task, you will explore the following:

1. Create two classes of the same name. Apply the class name to an element. Record your
observation in the text file.

12 Using external style sheets


The flexibility and power of CSS are best utilized when the CSS is external to the web page
document. An external style sheet is a text file with a .css file extension that contains CSS style
rules. The external style sheet file is associated with a web page by using the link element. This
approach provides a way for multiple web pages to be associated with the same external style
sheet file. The external style sheet file does not contain any HTML tags; it contains only CSS
style rules.

12.1 The link element

The link element associates an external style sheet with a web page. It is placed in the head
section of the page. The link element is a stand-alone, void tag. Three attributes are used with
the link element: rel, href, and type.

• The value of the rel attribute is “stylesheet”.

• The value of the href attribute is the name of the style sheet file.

• The value of the type attribute is “text/css”, which is the MIME type for CSS.

The type attribute is optional in HTML5 and required in XHTML. Code the following in the
head section of a web page to associate the document with the external style sheet named:
color.css
Note: This should be part of the <head> section of your HTML file.

31
1 <head>
2 <link rel="stylesheet" href="color.css" type="text/css">
3 </head>

Task 8: Using external CSS


You are going to create a simple style sheet and associate it with a basic HTML file, i.e. a
file with the main components of a HTML file. An example of this is shown in Lab 1 (or use
template.html if you have such a file).

Steps:

1. Create a .css file with only the following:


1 body{background-color: #0000FF;
2 color: #FFFFFF;}

2. Save this .css file as: external.css


3. Associate this CSS file to a copy of “template.html” (from Lab 1) by using the link
element. Modify the title and text in the body as needed.
4. Save your file as: external_CSS.html

In this task, you have created a simple CSS and have associated it with a simple HTML file.
This is just for you to test out how to associate a CSS to a HTML file. In the next tasks, you
will be creating something more complex.

Task 9: Applying an external style sheet to a website


In this task you will now use external style sheets to apply the styles you have earlier created
(the lavender coloured ones) to all three (3) of the pages of the web site you created in Lab 1.

Steps:

1. Put all the style elements you have created in this lab into a single CSS file. Put this file
into a folder (called “css”) in the root folder of your website.
2. Link all the files of the website you created in Lab 1 to this style sheet.
(Note: You will need to understand relative and absolute hyperlinks)
3. Save all your HTML files with the original file name. If you do not, you will need to
modify the links in the file as needed.

32
(Note: Move your entire root folder to another location and ensure that your web site still
looks and behaves the same way.)
4. Center all the text on the web site using the id selector in your CSS. Use these properties:
• margin-left: auto
• margin-right: auto
• width: 80%
You will apply this id by wrapping the contents of the body in a <div> environment. To
do this, all you need to do is add <div> just after the body opening tag in the HTML
file and add </div> before the body closing tag.
5. Put all your website files under a single folder. You will later have to put this folder into
your current working folder for submission.

Your web site folder structure should look like:


website_css . . . . . . . . . . . . . . . . . . . . . . . . . This folder/directory holds all your other
web site files).
css . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This folder/directory contains all CSS files,
which is currently only one).
external_css.css . . . . . . . . . . . . . . . This is your common CSS file for the whole
website. All other file should point to this
CSS file.
index.html . . . . . . . . . . . . . . . . . . . . . . . This is your home page.
contact.html . . . . . . . . . . . . . . . . . . . . . This is your contact page.
services.html . . . . . . . . . . . . . . . . . . . . . This is your services page.

33
Question(s) 5

1. What does CSS stand for?


2. Describe what is CSS and what it is used for.
3. What are the types of CSS that can be applied to a HTML document?
4. List what CSS properties are inherited and what are not.
5. Explain what happens when there is more than one CSS linked to a HTML
document.
6. Explain what happens when there is more than one CSS imported into a HTML
document.
7. Name another type of user agent apart from a web browser.
8. Describe how a user can apply they own style sheet (i.e. a user style sheet to a
web page.
9. Describe the differences between using @import versus <link> to use an style
sheet that is not part of the current HTML document.
10. Explain when you will use @import and <link> with examples of each.

13 Summary
In this lab, you will have done the following:

1. Apply colour and text styles using inline CSS, embedded CSS and external CSS.
2. Create your own CSS file and link it to a HTML file.
3. Apply an external CSS file to several HTML files.
4. Understand the concepts of cascade, specificity and inheritance.
5. Know how to declare selectors and combinators.

References
1. CSS from Maxdesign
2. Cascade and inheritance

Submission
In your submission archive, you should have the following files:

1. files you have been asked to specifically name

34
2. your observation file
3. your styled website (correctly named)

Note

As this is an official submission, you must not submit work that is NOT yours. Prevailing
academic malpractice rules apply. Please refer to your student handbook what they are.

Your archive should have the following format: Legend:

: These are folders/directories.


: These are files. No special formatting.

<00000000>_<LabNum>.zip. . . . . . . . . . . . . . . . This is the main archive.


<00000000> must be replaced
with your student ID). <Lab-
Num> is the word “Lab”
appended with the current lab
number (without spaces), e.g.
12345678_Lab2.zip.
task1
file1 from task1
file2 from task1 (where applicable)
all other files from task1 (where applicable)
task2
file1 from task2
all other files from task2 (where applicable)
(all other tasks for this part of the submission)
website_css. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This is for Task 9.
css
external_css.css
index.html
contact.html
services.html
All observations, discussion and conclusions
Answers to the questions for this part of the submission (if applicable)

35
Changelog
• Version 2.1
Date: 18 Aug 2020
1. Changed: PDF page layout.
2. Updated: Dates on the upper-right.

• Version 2.0
Date: 5 May 2020
1. Complete revamp of the lab sheet.

• Version 1.3
Date: 26 April 2020
1. Updated: Changed the stylesheet, tasks hyperlinks.
2. Updated: Structure of the lab sheet.
3. Added: Questions, icons for the submissions.

36

You might also like