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

P Elcteive 2 (Web Systems and Technolgies HTML-css-javascript-And-jquery

This document provides an instructional module for a course on web systems and technologies. It contains: 1) An introduction and foreword by the author explaining the purpose and structure of the manual. 2) A grading system section outlining the assessment criteria for labs, quizzes, projects, and exams. 3) A table of contents listing the chapters which cover HTML, CSS, JavaScript, and JQuery fundamentals.

Uploaded by

John Fuerzas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
202 views

P Elcteive 2 (Web Systems and Technolgies HTML-css-javascript-And-jquery

This document provides an instructional module for a course on web systems and technologies. It contains: 1) An introduction and foreword by the author explaining the purpose and structure of the manual. 2) A grading system section outlining the assessment criteria for labs, quizzes, projects, and exams. 3) A table of contents listing the chapters which cover HTML, CSS, JavaScript, and JQuery fundamentals.

Uploaded by

John Fuerzas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Instructional Module

in
P Elective 2
Web Systems and Technologies

LEODIVINO A. LAWAS , Ph.D.

THIS IS FOR INSTRUCTIONAL PURPOSES ONLY


NOT FOR SALE

Instructional Module created by : Leodivino A. Lawas


1 PythonDSP
FOREWORD

This Computer Laboratory manual is designed for use of the subject P Elective 2 111 Web

Development of the course Bachelor of Science in Information Technology (BSIT) of the College of

Technology in CEBU TECHNOLOGICAL UNIVERSITY – Main Campus. This course is designed for knowledge and

skills-based processes and operations needed for the fundamentals of Web Development on HTML, CSS,

JavaScript and JQuery.

In class, you will receive information at an expounded, comprehensive and other varied method to have

better understanding of the different approaches applicable to each specific topic. For best results, study and

practice your technical knowledge in Web Development between class sessions, and use of this manual for

additional skills and information.

LEODIVINO A. LAWAS, Ph.D.


Information Technology Faculty

Instructional Module created by : Leodivino A. Lawas


GRADING SYSTEM

1. Comprehensive (25%)
1.1 Laboratory Session (10%) - The presence of the student in the computer laboratory must be
productive to mold his/her consciousness regarding the importance of the subject in terms of
skills, theory and attitude.
 Laboratory performance refers to how the student maximizes time to achieve each specific
task/activities in terms of correct attitude towards learning.
 Proper use of Computer Facilities refers to the proper way of utilizing the different basic
programming fundamentals that the students must learn in order to achieve efficiency in
programming skills.
 Behavior refers to the concept that knowledge will be best applied if good behavior and
attitude in performing the laboratory activities are observed.
1.2 Quiz (15%) - Short quizzes will be accumulated per term.

2 Performance (60%)
2.1 Laboratory Activities
Performance activities are prepared for skills application and assessment of each topic
during laboratory session. An evaluation scorecard will serve as basis for rating each
performance of students in the laboratory as presented in evaluation procedure. If a student
fails to perform below 40% of the required worksheets/plates/performance activities (due to
unexcused absences, unsatisfactory works, etc.), he/she will automatically get a grade of 5.0.
Administration Jobs related to the course are considered a project/performance of a student.

3 Major Examination (15%)


Midterm and Final examinations and long quizzes must be taken to complete the course.
Failure to take these examinations will result to No Grade (NG) and must be complied to have
a grade.

STUDENT’S AGREEMENT

I have carefully read and understood the recommended general rules and practices while I
am in the Computer Laboratory. I agree to follow them and any other Computer Laboratory rules
my instructor will specify for my safety and success of each and every activity that I am going to
undertake.
I understand that irresponsible behavior has no place in the Computer Laboratory. The
potential effect posed of such behavior is of great value in my professional development.
I recognize my responsibility to follow these practices and precautions while I am inside the
laboratory.
Conforme:

________________________________
Signature over Printed Name/Date
________________________________
Course, Year & Section/Class Schedule

Noted by:

Instructional Module created by : Leodivino A. Lawas


___________________________
Computer Laboratory Instructor/Date
TABLE OF CONTENTS

Title Page i
Foreword ii
Acknowledgement iii
Grading System iv
Students Agreement v
Table of Contents vi
Vision, Mission, Goals and Objectives of the University 1
Laboratory Safety Precautions 2

Chapter 1: Hypertext Text Markup Language (HTML)

First Tagging Script 8


Tag Attribute 11
Table Tag with Attribute 12
Text Formatting Tag and attribute 15
Image Tag 16
List tag 17
Hyper Link 18
Forms 19
Chapter 2: Cascading Style Sheet (CSS) 26
Inline CSS 26
Embedded CSS 27
External CSS 29
Basic CSS Selector 31
Chapter 3: JavaScript 38
Data Types 41
Variables 42
Operators 46
Control Structures, loops and Functions 46
Event Handling 50

Instructional Module created by : Leodivino A. Lawas


Chapter 4: JQuery 52
Add JQuery Code 55
Get Inout for Users 61
Selectors 65
Select elements 66
Select class 67

Combining selectors 68

Multiple selectors 68

Select descendant element 68

Select child element 68

Attribute selector 69

Web References and Related Wrox Books 73

Instructional Module created by : Leodivino A. Lawas


Chapter 1
HTML

1.1 Introduction

In this chapter, various component of HTML are discussed to design a web page.
The basic structure for an HTML page is shown below.
• Entries inside the /< ... /> are known as tags. Most of the tags has an opening and closing
e.g. <head>(opening head) and </head> (closing head). Some of the tags do not have closing
tags e.g. <!DOCTYPE ...> and <br />. We need to write the HTML codes inside the tags.
• The comments are written between ‘<!–’ and ‘–>’.
• Here Line 1 gives the details of the ‘HTML version’ to the web-browser. The ‘html’ tells it is
version 5.
• The ‘head’ tag (Lines 3-5) contains the header related tags e.g. ‘title for the page’ and ‘links
for the css files’etc.
• The ‘body’ tag (7-11) contains the actual HTML code which is displayed on the web-browser.
Also, we add all the JavaScript related codes just before the closing body tag (</body>).

<!DOCTYPE html> <!-- tells browser above the html version -->
<html> <!-- beginning of the html document -->
<head>
<!-- header related tags e.g. title, links etc. -->
</head>
<body>
<!-- actual html document here -->
<!-- add JavaScript files here -->
</body>
</html>

1.2 First Tagging script

In below code, the message “HTML Lesson” is displayed on the HTML page. The Fig. 1.1 is the
resultant HTML page.
6

Instructional Module created by : Leodivino A. Lawas


• The title (Line 4) appears on the top of the browser.
• The tag <h1> is called ‘header’ tag, which has the larger size than the normal text (see the size
of ‘ Welcome to HTML Leo’).
• The tag <p> is called the ‘paragraph’ tag, which can be used to write the paragraphs. Basic
tags
<!DOCTYPE html>
<html>
<head>
<title>HTML Lesson</title>
</head>
<body>
<h1> Welcome to HTML Leo </h1>
<p> This is the first HTML code </p>
</body>
</html>
Fig. 1.1: First HTML Tagging Script

• The Table 1.1 shows the list of tags which are required for writing the basic ‘HTML’ codes i.e.
without any style e.g. bold, italics and numbering etc.

Table 1.1: List of basic tags


Tag Description Example
h1, ..., h6 Header tag h1 to h6 <h2> Hi </h2>
P paragraphs (Line changes at the <p> Hi </p>
end)
span No line change after span <span>Hi</span> Bye.
Div make division between contents <div> ... </div>
A Hyperlink < a href= ” ”>…..</a>
7

Instructional Module created by : Leodivino A. Lawas


center Move content to center <center> Hi </center>
Br Line break <br>…..</br>
Hr horizontal line <hr>….</hr
Pre preserve formatting <pre> .... </pre>
table insert table <table>…..</table>
• Let’s see the example of each of these tags,

Note: All the new codes are added below the previous codes in the ‘body’ tag. Therefore only newly
added codes are shown in the tutorial.

<h2> Heading 2 </h2>


<h6> Heading 6 </h6>

<p> This is paragraph </p>

<span> This is span.</span>


<span> The 'br' tag is used after span to break the line </span>
<br/>

<div style="color:blue;">
<--The 'div' tag can be used for formatting the tags inside it at once using 'style' and 'classes'␣
˓→
etc.--->

<p> This paragraph is inside the 'div' tag </p>

<span> This span is inside the 'div' tag </span> <br/>

</div>

<center>
<h3> Heading 3 is centered</h3>
<p><span> Centered span inside the paragraph.</span><p>
</center>

Two horizontal line is drawn using two 'hr' tag.


<hr />
<hr>

<pre> 'pre' tag preserve the formatting (good for writing codes)

# Python code
x=2y
=3
print(x+y)

Instructional Module created by : Leodivino A. Lawas


</pre>
Fig. 1.2 is the output of above code. Read the text to understand each tag,

Fig. 1.2: Basic tags : Attribute ‘style’ is used in ‘div’ tag

1.4 Attributes

In Fig. 1.2, we saw an example of attribute (i.e. style) which changed the color of all the elements to
‘blue’ inside the ‘div’ tag.

1.4.1 Attribute ‘name’ and ‘value’

• Attribute is defined inside the opening part of a ‘tag’. For example, in the below code, the
attribute ‘style’ is defined inside the ‘div’ tag.
<div style=”color:blue”>
</div>
An attribute has two parts i.e. ‘name’ and ‘value’. For example, in the above code, name and
value of the attribute are ‘style’ and ‘blue’ respectively.
1.4.2 Core attributes

Below are the three core attributes which are used frequently in web design.
• id : The ‘id’ is the unique name which can be given to any tag. This is very useful in
distinguishing the element with other elements.

Instructional Module created by : Leodivino A. Lawas


<p id=’para1’>This is paragraph with id’para1’</p>
<p id=’para2’>This is paragraph with id’para2’</p>
• class : The attribute ‘class’ can be used with multiple tags. This is very useful in making groups in
HTML design.
<p class=”c blue”> This is paragraph with class ’blue’</p>
<span class=”c blue”> This is span with class class ’blue’</span>
• style : We already see the example of style attribute, which can be used to change the
formatting of the text in HTML design. We can specify various styles which are discussed in
Chapter 2.
<p style="font-weight:bold; color:red;">Style attribute is used to bold and color</p>

Note: Above three attributes are used with ‘CSS (cascading style sheet)’ and JavaScript/jQuery, which
are the very handy tools to enhance the look and functionalities of the web-page respectively. The
CSS is discussed in Chapter 2, whereas JavaScript and jQuery are discussed in Chapter 4 and Chapter
5 respectively.
• Also we can define multiple attributes for one tag as shown below,

<p class="my_class" id="para_with_class" style="color:green"> Multiple attributes </p>


• The other useful attributes are listed in Table 1.2

Table 1.2: List of attributes


Name Values Description
Id user defined names <p id=’p_1’> Hi </p>
Class user defined names <p class=’p_class’> Hi </p>
Style CSS styles <p style=”color:red; font-weight:bold;”> Hi
</p>
Align left, right, center horizontal alignment
Width numeric value or % width of images and tables etc.
value
height numeric value height of images and tables etc.

10

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML
1.5 Tables

In this section, we will learn to draw tables along with some attributes which are discussed in Table 1.2.
Table 1.3 shows the list of tags available to create the table, which are used in Listing 1.1.

Table 1.3: Tags and attributes for creating tables


Tag Description
table beginning and end of table
tr row of table
th header cell
td data cell
Attributes

rowspan number of rows to merge


colspan number of columns to merge
border width of border
cellpadding width of whitespace between two
border
cellspacing width of whitespace within a
border
bgcolor background color
bordercolor color of border
width width of table (numeric or %)
height height of table (numeric)
caption caption for table

11

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML
• Some of the attributes of Table 1.3 are used in below example,

<html>
<!-- border-color, width and height -->
<table border="1" bordercolor="black" width="450" height="100">
<caption>Table 1 : Various tags of table</caption>
<tr bgcolor="red" > <!-- row -->
<th>Column 1</th> <!-- header -->
<th>Column 2</th>
<th>Column 3</th>
</tr>

<tr bgcolor="cyan"> <!-- background color -->


<td>Data 1</td> <!-- data -->
<td>Data 2</td>
<td>Data 3</td>
</tr>

<tr bgcolor="yellow"> <!-- row -->


<td colspan="2">New Data 1</td> <!-- column span -->
<td>New Data 2</td> <!-- data --> </tr>
</table>

<!-- width in % -->


<table border="1" bordercolor="black" width="80%" height="100">
<caption> Table 2 : Width is 80%</caption>
<tr bgcolor="red" >
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th> </tr>
<tr bgcolor="cyan"> <!-- row -->
<td>Data 1</td> <!-- data -->
<td>Data 2</td>
<td>Data 3</td>
</tr>

</table>

Listing 1.1: Table with border and color


</html>

12

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML
Fig. 1.3 is the output of below code,

1.6 Text formatting

In this section, we will see some of the text formatting options (see Table 1.4) e.g. bold, italic, subscript
and strike etc.

Table 1.4: Text formatting


Tag Description
b bold
i italic
u, ins underline
strike, strike
del
Sup superscript
Sub subscript
Big big size text
Small small size
text

• Below are the some of the examples of text formatting, whose results are shown in Fig. 1.4,
<html>
<!-- Text formatting -->
<p>This is <b>bold</b> text</p>
<p>This is <strike>striked</strike> text</p>
<p>This is <sub>subscript</sub> text</p>
<p>This is <i>Italic</sub> text</p>
13

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML
<p>This is <sub>Underline</sub> text</p>
<p>This is <sup>superscript</sub> text</p>
<p>This is <big>Big</sub> text</p>
<p>This is <small>small</sub> text</p></html>

Fig. 1.4: Text formatting

1.7 Images

Image tag has two important attribues i.e. ‘src’ and ‘alt’ as described below,
• src : tells the location of ‘image’ file e.g. in Line 2 the image ‘logo.jpg’ will be searched inside the
folder
‘img’.

• alt : is the ‘alternate text’ which is displayed if image is not found. For example, in Line 6, the
name of the image is incorrectly written i.e. ‘logoa’ (instead of ‘logo’), therefore the value of ‘alt’
i.e. ‘Missing Logo.jpg’ will be displayed as shown in Fig. 1.5.

<html>
<!-- Images -->
<img src="profile.jpg" alt="profile.jpg" width="50%"/>
<br/> <br/>
<img src="Picture1.png" alt="Picture1.png" width="20%"/>

14

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML

</html>

Fig. 1.5: Images

Note: We can use other attributes as well e.g. ‘height’, ‘align’ and ‘border’ etc.

1.8 Lists

There are three type of lists in HTML,


• Unordered list : bullet are used in it (see Lines 2 and 9)
• Ordered list : numbers are used in it (see Lines 15, 22 and 28)
• Definition list : This can be used for writing definitions in HTML (see Line 35)

15

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML
<html>
<!-- Lists -->
<!-- unordered list -->
<ul> Unordered List
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ul>
<ul type="circle"> Change bullets : 'square', 'circle' or 'disc'
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ul>
Fig
<!-- ordered list -->
1.6
<ol> Ordered List
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ol>
<ol type='i'> Change style : 'i', 'I', '1', 'a' or 'A'
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ol>
<ol type='i' start="5"> Start from 'v'
<li>Pen</li>
<li>Pencil</li>
<li>Eraser</li>
</ol>

<!-- Definition list -->


<dl>
<dt> <h4>HTML Definition List</h4> </dt>
<dd> HTML is easy </dd>
<dd> HTML is good </dd>
<dl>
</html>

The outputs of above codes are shown in Fig. 1.6

1.9 Links

16

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML

<!-- links -->


< a href="http://www.facebook.com"> click here to go to
facebook </a>

17

Instructional Module created by : Leodivino A. Lawas


Chapter 1. HTML

Instructional Module created by : Leodivino A. Lawas


18
Chapter 1. HTML

Fig 1.7

Note: We can change the color of the links using ‘alink (active link)’, ‘link’ and ‘vlink (visited link’, by
defining these attributes in the ‘body tag’ as shown below,
<body alink="green" link="blue" vlink="red">

1.10 Forms

Forms can have different types of controls to collect the input-data from users, which are listed
below and shown in Table 1.5,
• Text input
• Text area
• Radio button
• Checkbox
• Select box
• File select
• Buttons
• Submit and reset buttons
• Hidden input

Table 1.5: List of control inputs and their attributes


Control Attributes Values Description
Input : text type text, password

value user-defined initial value in the area

Instructional Module created by : Leodivino A. Lawas


19
Chapter 1. HTML

name user-defined name send to server

size numeric value width of the text area

maxlength numeric value maximum number of characters

Input : radio type radio

name user-defined name send to server

value user-defined value of the button if selected


value
checked check the button by default

Input : check type checkbox


box
name user-defined name send to server

value user-defined value of the box if selected


value
checked check the box by default

Input : button type button trigger client side script


submit submit the form and run ‘action’

reset reset form

image create image button

method get, post get or post method

action user-defined action to perform on submit

Input : hidden type hidden will not display on html, but can be
used
for sending information to server

Selection box name user-defined name send to server


size numeric value enables scroll (default dropdown)

multiple numeric value select multiple items

value user-defined value of the item if selected


value
selected select item by default

Text area rows, cols numeric value number of rows and cols
name user-defined name send to server
• Below are the exmaple of the control inputs described in Table 1.5
<!-- Forms -->

Instructional Module created by : Leodivino A. Lawas


20
Chapter 1. HTML

<form>
<h4>Text input </h4>
Name : <input type="text" name="user_name" size="4" value="e.g. meher21"
maxlength="10"><br> Password : <input type="password" name="user_pass" ><br>

<h4> Radio button: name should be


same</h4> <input type="radio"
name="r_gender"> Male
<input type="radio" name="r_gender"> Female
<input type="radio" name="r_gender" checked> Infant

<h4> Check box : name should be different</h4>


<input type="checkbox" name="c_male" checked>
Male <input type="checkbox" name="c_female">
Female
<input type="checkbox" name="c_infant"> Infant

<h4> Select box : drop-down</h4>


<select name="s_box">
<option value="s_male">Male</option>
<option value="s_female" selected>Female</option>
<option value="s_infant">Infant</option>
</select>

<h4> Select box : scroll</h4>

<select name="s_box" size="4" multiple>


<option value="s_male" selected>Male</option>
<option value="s_female" selected>Female</option>
<option value="s_infant">Infant 1</option>
<option value="s_infant" selected>Infant 2</option>
<option value="s_infant">Infant 3</option>
<option value="s_infant">Infant 4</option>
</select>

<h4> Text area</h4>


<textarea rows="10" cols="80" name="txt_area">Initial
Text x = 2 y = 3
</textarea> <!-- formatting work as pre -->

</form>
Fig. 1.7 is the output of above code,

Instructional Module created by : Leodivino A. Lawas


21
Chapter 1. HTML

• Below is the code which shows the working of various buttons. Note that method and action are
defined in this form, which will be triggered on ‘submit’ button. Lastly, ‘hidden’ option is used in
this example.
<form method="get|post" action="jquery.html">
<h4> Buttons and Hidden</h4>

Name : <input type="text" name="user_name" size="4" value="Meher"


maxlength="16"><br> Password : <input type="password" name="user_pass" ><br>

<input type="button" onclick="alert('Hello')" name="b_alert" value="Say Hello"/><br>


<input type="submit" name="b_submit" value="Go to
jQuery"/> <input type="reset" name="b_reset"
value="Reset"/><br>

<input type="hidden" name="h_data" value="html_tutorial">


</form>
Fig. 1.8 is the output of above code,

Fig. 1.7: Various control inputs for creating form

Instructional Module created by : Leodivino A. Lawas


22
Chapter 1. HTML

Fig. 1.8: Various buttons and hidden-input in the form

Instructional Module created by : Leodivino A. Lawas


23
Additional Tag for example

<html>
<head>
<title>
Map individual Profiling
</title>
</head>
<body>
<p>
map location
</div class="mapouter">
<div class="gmap_canvas">
<iframe width="400" height="400"
id="gmap_canvas"
src="https://maps.google.com/maps
?q=Deca Homes Tisa t%20of
%20cebu%20carbon
market&t=&z=13&ie=UTF8&iwloc=&
output=embed" frameborder="0"
scrolling="no" marginheight="0"
marginwidth="0">
</iframe>
</div>
<style>.mapouter{position:relative;t
ext-
align:right;height:600px;width:700px
;}.gmap_canvas
{overflow:hidden;background:none!
important;height:500px;width:600px
;}
</style>
<form>
<input type="radio">
Enter your username:
<input type="text">
<br>
<input type="checkbox">
Enter your password:
<input type="password">
</br>
<br>
<select>
<option>Icecream with
lugaw</option>
<option>Icecream with
mongos</option>
<option>Icecream with prito nga
pancit</option>
Instructional Module created by : Leodivino A. Lawas
<option>Icecream with mango nga
pikas nga buwad</option>
</br>
</select>
<br>
Komentaryo mo ni sir here
</br>
<textarea rows="10" cols="15">
</textarea>
</br>
<input type="submit">
<input type="reset">
</br>
</p>
<table width="190" border="1"
cellpadding="7">
<tr>
<th rowspan="3"></th>
<th rowspan="3"></th>
<th rowspan="3"></th>
<th rowspan="3"></th>
</tr>
</table>
</form>
</body>
</html>

25
Instructional Module created by : Leodivino A. Lawas
Chapter 2

Cascading Style Sheets (CSS)

2.1 Introduction

CSS is used to enhance the look of the web page. In Section 1.4.2, we saw the attribute ‘style’, which is
used for changing the color of the text. Let’s rewrite the example of ‘style’ as shown in next section.

A CSS rule consists of a selector and a declaration block.

CSS Syntax

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

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks are
surrounded by curly braces.

26
Instructional Module created by : Leodivino A. Lawas
Example :

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

Example Explained

 p is a selector in CSS (it points to the HTML element you want to style: <p>).
 color is a property, and red is the property value
 text-align is a property, and center is the property value

2.1.1 Inline CSS

• Below code is an example of ‘inline CSS’, where the styles are defined inside the individual tags.

<!-- css.html -->

<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>

</head>
<body>

<h3 style="color:blue"> Heading 1 </h3>


<h3 style="color:blue"> Heading 3 </h3>
<h3 style="color:blue"> Heading 3 </h3>

</body>
</html>

27
Instructional Module created by : Leodivino A. Lawas
In the above code, we have three ‘headings’ with font-color as ‘blue’. Suppose, we want to change the
color to red, then we must go to to individual ‘h3’ tag and then change the color. This is easy in this case,
but if we have 100 headings in 5 different ‘html’ files, then this process is not very handy. In such cases,
CSS can be quite useful as shown in next section. Another Example Below

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

28
Instructional Module created by : Leodivino A. Lawas
2.1.2 Embedded CSS

In the below code, the style is embedded inside the ‘style’ tag as shown in Lines 8-17. Here, we have
defined two classes i.e. ‘h3_blue (Lines 21-23)’ and ‘h3_red (Lines 26-28)’. Then, the selectors at Lines 9
and 13 targets the class ‘h3_blue’ & ‘h3_red’, and change the color to blue and red respectively. In this
chapter, we will discuss the selectors (e.g. h3.h3_blue) in more details.

Note:
• In CSS, the comments are written between /* and */.

• CSS has three parts,


– Selectors e.g. p, h3.h3_blue
– Properties e.g. color
– Values of properties e.g. red

<!-- css.html -->

<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
<style type="text/css"> h3.h3_blue{
/*change color to blue*/ color:
blue;
}

h3.h3_red{ /*change color to red*/


color:red;
}
</style>
</head>
<body>
<h3 class='h3_blue'> Heading 1 </h3>
<h3 class='h3_blue'> Heading 3 </h3>
<h3 class='h3_blue'> Heading 3 </h3>

<h3 class='h3_red'> Heading 1 </h3>


<h3 class='h3_red'> Heading 3 </h3>
<h3 class='h3_red'> Heading 3 </h3>

29
Instructional Module created by : Leodivino A. Lawas
</body>
</html>
1
• Below is the output of above code,

Fig.
2.1: Embedded CSS

2.1.3 External CSS

We can write the ‘CSS’ code in different file and then import the file into ‘html’ document as shown in
this section. In this way, we can manage the files easily.
• The ‘CSS’ code is saved in the file ‘my_css.css’ which is saved inside the folder ‘asset/css’.
/* asset/css/my_css.css */

h3.h3_blue{ col
or: blue;
}

h3.h3_red{ color:r
ed;
}
• Next, we need to import the CSS file into the ‘html’ file as shown in Line 7.

<!-- css.html -->

30
Instructional Module created by : Leodivino A. Lawas
<!DOCTYPE html>
<html>
<head>
<title>CSS Tutorial</title>
<link rel="stylesheet" type="text/css" href="mycss.css">
</head>
<body>

<h3 class='h3_blue'> Heading 1 </h3>


<h3 class='h3_blue'> Heading 3 </h3>
<h3 class='h3_blue'> Heading 3 </h3>

<h3 class='h3_red'> Heading 1 </h3>


<h3 class='h3_red'> Heading 3 </h3>
<h3 class='h3_red'> Heading 3 </h3>

</body>
</html>

31
Instructional Module created by : Leodivino A. Lawas
2.2 Basic CSS Selectors

There are three types of selectors in CSS,


• Element : can be selected using it’s name e.g. ‘p’, ‘div’ and ‘h1’ etc.
• Class : can be selected using ‘.className’ operator e.g. ‘.h3_blue’.
• ID : can be selected using ‘#idName’ e.g. ‘#my_para’.
We will use following HTML for understanding the selectors,
2.3. Hierarchy

<!-- css.html -->

<!DOCTYPE html>
<html>
<head>
<title>CSS Selectors</title>
<link rel="stylesheet" type="text/css" href="asset/css/my_css.css">
</head>
<body>
<h3>CSS Selectors</h3>

<p class='c_head'> Paragraph with class 'c_head' </p>


<p id='i_head'> Paragraph with id 'i_head' </p>

</body>
</html>

• Below code shows the example of different selectors, and the output is shown in Fig. 2.2

/* asset/css/my_css.css */

/*element
selection*/
h3 {
color:
blue; }

/*class selection*/
.c_head{ font-family:
cursive; color: orange; }

32
Instructional Module created by : Leodivino A. Lawas
/*id selection*/
#i_head{ font-variant:
small-caps; color: red;
}

Fig. 2.2: Selectors : element, class and id

2.3 Hierarchy

In previous section, we saw the example of selectors. In this section, we will understand the hierarchy of
the styling-operations.

Important: Below is the priority level for the CSS,


• Priority level :
– ID (highest priority)
– Class
– Element
• If two CSS has same priority, then CSS rule at the last will be applicable.

• Below is the html code with following tags,


– ‘p’ tag
– ‘p’ tag with class ‘c_head’
– ‘p’ tag with class ‘c_head’ and id ‘i_head’

<!-- css.html -->


33
Instructional Module created by : Leodivino A. Lawas
<!DOCTYPE html>
<html>
<head>
<title>CSS Selectors</title>
<link rel="stylesheet" type="text/css" href="my_css.css">
</head>
<body>
<p>Paragraph</p>

<p class='c_head'> Paragraph with class 'c_head' </p>


<p class='c_head' id='i_head'> Paragraph with class 'c_head' and id 'i_head' </p>

</body>
</html>

Below is the CSS code. Let’s understand the formatting of all three ‘p’ tags individually. The results are
shown in Fig. 2.3.
• ‘p’ tag at Line 13 of html : Since, ‘id’ has highest priority, therefore CSS rule for #i_head’ (Line
12) will not be overridden by Line 24; hence the color is red. Line 13 has ‘p’ tag, therefore ‘font-
variant’ rule will be applied by Line 17. Also, this tag has class ‘c_head’, therefore ‘font’ will be
set to ‘cursive’. Hence, the line is “all-caps with font-cursive in red color”.
• ‘p’ tag at Line 12 of html : Similarly, the ‘head’ tag has higher priority than ‘element’ therefore
color of this line is oranage and font-family is ‘cursive’. Also, Line 17 will make it all caps
• ‘p’ tag at Line 10 of html : Color defined at Line 18 will be overridden by Line 24; hence the color
will be blue. Also, Line 17 will make it all caps.

/* my_css.css */

/*class selection*/
.c_head{ font-family:
cursive;
color: orange; /*override the blue color*/
}

/*id selection*/
#i_head{ color
: red;
}

/*element selection*/
p{
font-variant: small-caps;
color: blue;
}

34
Instructional Module created by : Leodivino A. Lawas
2.4. More selectors

/*element selection*/
p{
color: green;
}

Fig. 2.3: Priority level for CSS rule

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one
unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of
the element.

Example
The CSS rule below will be applied to the HTML element with id="para1": 

#para1 {
  text-align: center;
  color: red;
}

35
Instructional Module created by : Leodivino A. Lawas
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.

To select elements with a specific class, write a period (.) character, followed by the
class name.

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

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

<!DOCTYPE html>
<html>
<head>
<style>
p.center {
text-align: center;
color: red;
}
</style>
</head>
<body>

<h1 class="center">This heading will not be affected</h1>


<p class="center">This paragraph will be red and center-aligned.</p>

</body>
</html>

The CSS Universal Selector


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

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

36
Instructional Module created by : Leodivino A. Lawas
* {
  text-align: center;
  color: blue;
}

The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.

Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):

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

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

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

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

To group selectors, separate each selector with a comma.

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

h1, h2, p {


  text-align: center;
  color: red;
}

2.4 More selectors

37
Instructional Module created by : Leodivino A. Lawas
Table 2.1 shows the combinations of selectors to target the various elements of the HTML. Also, some of
the example of ‘Attribute selector’ is shown in this section.

Table 2.1: List of selectors


Selectors Description
h1, p, span etc. element selector
.className class selector
#idName id selector
* Universal selector (selects everything)
h1.className select h1 with class ‘className’
h1#idName select h1 with id ‘idName’
p span descendant selector (select span which is
inside p)
p > span child selector (‘span’ which is direct
descendant of ‘p’)
h1, h2, p group selection (select h1, h2 and p)
span[my_id] select ‘span’ with attribute ‘my_id’
span[my_id=m_span select ‘span’ with attribute ‘my_id=m_span’
]
2.4.1 Attribute selector

• Add below code at the end of the html file. In these lines ‘custom attributes’ are added (i.e.
my_id).
<!-- css.html -->

<span my_id='m_span'> Span with attribute 'my_id' with value 'm_span' </span> <br>
<span my_id='m_span2'> Span with attribute 'my_id' with value 'm_span2' </span>

• These custom attributes can be selected as below,


/*attribute selection*/
span[my_id] { /* select 'span' with attribute 'my_id' */ color: green; font-
weight: bold

span[my_id=m_span] { /* select 'span' with attribute 'my_id = m_span' */ color:


red; }

38
Instructional Module created by : Leodivino A. Lawas
2.5 More properties

Table 2.2 shows the some more important properties which can be used in CSS,

Table 2.2: More CSS properties


Propert Syntax Description/possible values
y
size 20% size = 20%
20px 20 pixel

2em 2*font-size

2mm, 2cm, 2in 2 mm, cm and inch

color names e.g. red, blue, green


hex code (#RRGGBB or #RGB) #FFF000 or #FFF

rgb(num, num, num) rgb(0, 0, 255) or rgb(20%, 10%,


70%)
link a:link a:link {color: red}
a:hover

a:visited

a:active

Font font-family serif, cursive


font-style normal, italic, oblique

font-variant normal, small-caps

font-weight normal, bold, bolder, lighter, 100-


900
font-size 10px, small, medium, large etc.

Text color red, #FFF


letter-spacing 10px

word-spacing 10 px

text-align right, left, center

text-decoration underline, overline, line-through,


none
text-transform capitalize, uppercase, lowercase,
none
white-space pre, normal, nowrap

text-shadow text-shadow:5px 5px 8px red;

Image border ‘1px’, or ‘1px solid blue’


39
Instructional Module created by : Leodivino A. Lawas
height, width 100px, 20%

Border border-style solid, dashed, dotted, double,


none etc.
border-top-style

border-bottom-style

border-left-style

border-right-style

border-width 4px, 4pt

border-bottom-width similarly use ‘top’, ‘left’, ‘right’

border (shortcut) 1px solid blue’

Margin margin, margin-left etc.

Padding padding (top, bottom, left, ‘10px 10px 2px 2px’ or ‘10px 2px’
right)
padding-right, padding-left
etc.

40
Instructional Module created by : Leodivino A. Lawas
CSS Backgrounds
❮ PreviousNext ❯

The CSS background properties are used to add background effects for elements.

In these chapters, you will learn about the following CSS background properties:

 background-color
 background-image
 background-repeat
 background-attachment
 background-position
 background (shorthand property)

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

Example
The background color of a page is set like this:

body {
  background-color: lightblue;
}
Try it Yourself »

With CSS, a color is most often specified by:

 a valid color name - like "red"


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

Look at CSS Color Values for a complete list of possible color values.


41
Instructional Module created by : Leodivino A. Lawas
Other Elements
You can set the background color for any HTML elements:

Example
Here, the <h1>, <p>, and <div> elements will have different background colors: 

h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

p {
  background-color: yellow;
}

CSS Background Image
❮ PreviousNext ❯

CSS background-image
The background-image property specifies an image to use as the background of an
element.

By default, the image is repeated so it covers the entire element.

Example
Set the background image for a page: 

body {
  background-image: url("paper.gif");
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »

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

body {
  background-image: url("bgdesert.jpg");
}
Try it Yourself »

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

The background image can also be set for specific elements, like the <p> element:

Example
p {
  background-image: url("paper.gif");
}
Try it Yourself »

CSS Background Image Repeat


❮ PreviousNext ❯

CSS background-repeat
By default, the background-image property repeats an image both horizontally and
vertically.

Some images should be repeated only horizontally or vertically, or they will look
strange, like this:

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

Instructional Module created by : Leodivino A. Lawas


Try it Yourself »

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


background will look better:

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

CSS Background Attachment
❮ PreviousNext ❯

CSS background-attachment
The background-attachment property specifies whether the background image should scroll
or be fixed (will not scroll with the rest of the page):

Example
Specify that the background image should be fixed:

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

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

body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
Instructional Module created by : Leodivino A. Lawas
  background-attachment: scroll;
}

CSS background - Shorthand property


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

Instead of writing:

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

You can use the shorthand property background:

Example
Use the shorthand property to set the background properties in one declaration:

body {
  background: #ffffff url("img_tree.png") no-repeat right top;
}
Try it Yourself »

When using the shorthand property the order of the property values is:

 background-color
 background-image
 background-repeat
 background-attachment
 background-position

It does not matter if one of the property values is missing, as long as the other ones
are in this order. Note that we do not use the background-attachment property in the
examples above, as it does not have a value.

Test Yourself with Exercises!


Exercise 1 »Exercise 2 »Exercise 3 »Exercise 4 »Exercise 5 »

Instructional Module created by : Leodivino A. Lawas


All CSS Background Properties

Property Description

background Sets all the background properties in one declaration

background- Sets whether a background image is fixed or scrolls with


attachment the rest of the page

background-clip Specifies the painting area of the background

background-color Sets the background color of an element

background-image Sets the background image for an element

background-origin Specifies where the background image(s) is/are positioned

background-position Sets the starting position of a background image

background-repeat Sets how a background image will be repeated

background-size Specifies the size of the background image(s)

Instructional Module created by : Leodivino A. Lawas


CSS Borders
❮ PreviousNext ❯

The CSS border properties allow you to specify the style, width, and color of an
element's border.

I have borders on all sides.

I have a red bottom border.

I have rounded borders.

I have a blue left border.

CSS Border Style


The border-style property specifies what kind of border to display.

The following values are allowed:

 dotted - Defines a dotted border


 dashed - Defines a dashed border
 solid - Defines a solid border
 double - Defines a double border
 groove - Defines a 3D grooved border. The effect depends on the border-color
value
 ridge - Defines a 3D ridged border. The effect depends on the border-color value
 inset - Defines a 3D inset border. The effect depends on the border-color value
 outset - Defines a 3D outset border. The effect depends on the border-color value
 none - Defines no border
Instructional Module created by : Leodivino A. Lawas
 hidden - Defines a hidden border

The border-style property can have from one to four values (for the top border, right
border, bottom border, and the left border).

Example
Demonstration of the different border styles:

p.dotted {border-style: dotted;}
p.dashed {border-style: dashed;}
p.solid {border-style: solid;}
p.double {border-style: double;}
p.groove {border-style: groove;}
p.ridge {border-style: ridge;}
p.inset {border-style: inset;}
p.outset {border-style: outset;}
p.none {border-style: none;}
p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}

Result:

A dotted border.

A dashed border.

A solid border.

A double border.

A groove border. The effect depends on the border-color value.

A ridge border. The effect depends on the border-color value.

An inset border. The effect depends on the border-color value.

An outset border. The effect depends on the border-color value.

No border.

A hidden border.

Instructional Module created by : Leodivino A. Lawas


A mixed border.

Try it Yourself »

CSS Border Width
❮ PreviousNext ❯

CSS Border Width


The border-width property specifies the width of the four borders.

The width can be set as a specific size (in px, pt, cm, em, etc) or by using one of the
three pre-defined values: thin, medium, or thick:

Example
Demonstration of the different border widths:

p.one {
  border-style: solid;
  border-width: 5px;
}

p.two {
  border-style: solid;
  border-width: medium;
}

p.three {
  border-style: dotted;
  border-width: 2px;
}

p.four {
  border-style: dotted;
  border-width: thick;
}

Result:

Instructional Module created by : Leodivino A. Lawas


5px border-width
medium border-width
2px border-width
thick border-width

CSS Border Color
❮ PreviousNext ❯

CSS Border Color


The border-color property is used to set the color of the four borders.

The color can be set by:

 name - specify a color name, like "red"


 HEX - specify a HEX value, like "#ff0000"
 RGB - specify a RGB value, like "rgb(255,0,0)"
 HSL - specify a HSL value, like "hsl(0, 100%, 50%)"
 transparent

Note: If border-color is not set, it inherits the color of the element.

Example
Demonstration of the different border colors:

p.one {
  border-style: solid;
  border-color: red;
}

p.two {
  border-style: solid;
  border-color: green;
}

p.three {
  border-style: dotted;
  border-color: blue;
}

Instructional Module created by : Leodivino A. Lawas


CSS Border - Individual Sides
From the examples on the previous pages, you have seen that it is possible to specify a
different border for each side.

In CSS, there are also properties for specifying each of the borders (top, right, bottom,
and left):

Example
p {
  border-top-style: dotted;
  border-right-style: solid;
  border-bottom-style: dotted;
  border-left-style: solid;
}

Margins are used to create space around elements, outside of any defined borders.

This element has a margin of 70px.

Try it Yourself »

CSS Margins
The CSS margin properties are used to create space around elements, outside of any
defined borders.

With CSS, you have full control over the margins. There are properties for setting the
margin for each side of an element (top, right, bottom, and left).

Margin - Individual Sides


CSS has properties for specifying the margin for each side of an element:

 margin-top

Instructional Module created by : Leodivino A. Lawas


 margin-right
 margin-bottom
 margin-left

All the margin properties can have the following values:

 auto - the browser calculates the margin


 length - specifies a margin in px, pt, cm, etc.
 % - specifies a margin in % of the width of the containing element
 inherit - specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example
Set different margins for all four sides of a <p> element:

p {
  margin-top: 100px;
  margin-bottom: 100px;
  margin-right: 150px;
  margin-left: 80px;
}
Try it Yourself »

Margin - Shorthand Property


To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin


properties:

 margin-top
 margin-right
 margin-bottom
 margin-left

So, here is how it works:

If the margin property has four values:

Instructional Module created by : Leodivino A. Lawas


 margin: 25px 50px 75px 100px;
o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px

Example
Use the margin shorthand property with four values:

p {
  margin: 25px 50px 75px 100px;
}
Try it Yourself »

If the margin property has three values:

 margin: 25px 50px 75px;


o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px

Example
Use the margin shorthand property with three values: 

p {
  margin: 25px 50px 75px;
}
Try it Yourself »

If the margin property has two values:

 margin: 25px 50px;


o top and bottom margins are 25px
o right and left margins are 50px

Example
Use the margin shorthand property with two values: 

p {
  margin: 25px 50px;
}
Try it Yourself »

Instructional Module created by : Leodivino A. Lawas


If the margin property has one value:

 margin: 25px;
o all four margins are 25px

Example
Use the margin shorthand property with one value: 

p {
  margin: 25px;
}
Try it Yourself »

The auto Value


You can set the margin property to auto to horizontally center the element within its
container.

The element will then take up the specified width, and the remaining space will be split
equally between the left and right margins.

Example
Use margin: auto:

div {
  width: 300px;
  margin: auto;
  border: 1px solid red;
}
Try it Yourself »

The inherit Value


This example lets the left margin of the <p class="ex1"> element be inherited from the
parent element (<div>):

Instructional Module created by : Leodivino A. Lawas


Example
Use of the inherit value:

div {
  border: 1px solid red;
  margin-left: 100px;
}

p.ex1 {
  margin-left: inherit;
}

CSS Padding
❮ PreviousNext ❯

Padding is used to create space around an element's content, inside of any defined
borders.

This element has a padding of 70px.

Try it Yourself »

CSS Padding
The CSS padding properties are used to generate space around an element's content,
inside of any defined borders.

With CSS, you have full control over the padding. There are properties for setting the
padding for each side of an element (top, right, bottom, and left).

Instructional Module created by : Leodivino A. Lawas


Padding - Individual Sides
CSS has properties for specifying the padding for each side of an element:

 padding-top
 padding-right
 padding-bottom
 padding-left

All the padding properties can have the following values:

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


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

Note: Negative values are not allowed.

Example
Set different padding for all four sides of a <div> element:  

div {
  padding-top: 50px;
  padding-right: 30px;
  padding-bottom: 50px;
  padding-left: 80px;
}
Try it Yourself »

Padding - Shorthand Property


To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding


properties:

 padding-top
 padding-right
 padding-bottom
 padding-left

Instructional Module created by : Leodivino A. Lawas


So, here is how it works:

If the padding property has four values:

 padding: 25px 50px 75px 100px;


o top padding is 25px
o right padding is 50px
o bottom padding is 75px
o left padding is 100px

Example
Use the padding shorthand property with four values:

div {
  padding: 25px 50px 75px 100px;
}
Try it Yourself »

If the padding property has three values:

 padding: 25px 50px 75px;


o top padding is 25px
o right and left paddings are 50px
o bottom padding is 75px

Example
Use the padding shorthand property with three values: 

div {
  padding: 25px 50px 75px;
}
Try it Yourself »

If the padding property has two values:

 padding: 25px 50px;


o top and bottom paddings are 25px
o right and left paddings are 50px

Example
Use the padding shorthand property with two values: 

Instructional Module created by : Leodivino A. Lawas


div {
  padding: 25px 50px;
}
Try it Yourself »

If the padding property has one value:

 padding: 25px;
o all four paddings are 25px

Example
Use the padding shorthand property with one value: 

div {
  padding: 25px;
}
Try it Yourself »

Padding and Element Width


The CSS width property specifies the width of the element's content area. The content
area is the portion inside the padding, border, and margin of an element (the box
model).

So, if an element has a specified width, the padding added to that element will be
added to the total width of the element. This is often an undesirable result.

Example
Here, the <div> element is given a width of 300px. However, the actual width of the
<div> element will be 350px (300px + 25px of left padding + 25px of right padding):

div {
  width: 300px;
  padding: 25px;
}
Try it Yourself »

To keep the width at 300px, no matter the amount of padding, you can use the box-
sizing property. This causes the element to maintain its actual width; if you increase the
padding, the available content space will decrease.

Instructional Module created by : Leodivino A. Lawas


Example
Use the box-sizing property to keep the width at 300px, no matter the amount of
padding:

div {
  width: 300px;
  padding: 25px;
  box-sizing: border-box;
}
Try it Yourself »

CSS Height and Width


❮ PreviousNext ❯

The CSS height and width properties are used to set the height and width of an


element.

The CSS max-width property is used to set the maximum width of an element.

This element has a height of 50 pixels and a width of 100%.

Try it Yourself »

CSS Setting height and width


The height and width properties are used to set the height and width of an element.

The height and width properties do not include padding, borders, or margins. It sets the
height/width of the area inside the padding, border, and margin of the element.

Instructional Module created by : Leodivino A. Lawas


CSS height and width Values
The height and width properties may have the following values:

 auto - This is default. The browser calculates the height and width
 length - Defines the height/width in px, cm etc.
 % - Defines the height/width in percent of the containing block
 initial - Sets the height/width to its default value
 inherit - The height/width will be inherited from its parent value

CSS height and width Examples


This element has a height of 200 pixels and a width of 50%

Example
Set the height and width of a <div> element:

div {
  height: 200px;
  width: 50%;
  background-color: powderblue;
}

The CSS Box Model


In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:

Explanation of the different parts:

 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space between
elements. 

Instructional Module created by : Leodivino A. Lawas


Example
Demonstration of the box model:

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

CSS Text
❮ PreviousNext ❯

CSS has a lot of properties for formatting text.

TEXT FORMATTING
This text is styled with some of the text formatting
properties. The heading uses the text-align, text-transform,
and color properties. The paragraph is indented, aligned, and
the space between characters is specified. The underline is
removed from this colored "Try it Yourself" link.

Try it Yourself »

Text Color
The color property is used to set the color of the text. The color is specified by:

 a color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"
Instructional Module created by : Leodivino A. Lawas
Look at CSS Color Values for a complete list of possible color values.

The default text color for a page is defined in the body selector.

Example
body {
  color: blue;
}

h1 {
  color: green;
}
Try it Yourself »

CSS Icons
❮ PreviousNext ❯

Icons can easily be added to your HTML page, by using an icon library.

  

  

  

How To Add Icons


The simplest way to add an icon to your HTML page, is with an icon library, such as
Font Awesome.

Add the name of the specified icon class to any inline HTML element (like <i> or <span>).

All the icons in the icon libraries below, are scalable vectors that can be customized with
CSS (size, color, shadow, etc.)
Instructional Module created by : Leodivino A. Lawas
Font Awesome Icons
To use the Font Awesome icons, go to fontawesome.com, sign in, and get a code to add
in the <head> section of your HTML page:

<script src="https://kit.fontawesome.com/ yourcode.js" crossorigin="anonymous"></script>

Read more about how to get started with Font Awesome in our Font Awesome 5
tutorial.

Note: No downloading or installation is required!

Example
<!DOCTYPE html>
<html>
<head>
<script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"><
/script>
</head>
<body>

<i class="fas fa-cloud"></i>
<i class="fas fa-heart"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>

</body>
</html>

Styling Links
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).

Example
a {
  color: hotpink;
}
Try it Yourself »

In addition, links can be styled differently depending on what state they are in.


Instructional Module created by : Leodivino A. Lawas
The four links states are:

 a:link - a normal, unvisited link


 a:visited - a link the user has visited
 a:hover - a link when the user mouses over it
 a:active - a link the moment it is clicked

Example
/* unvisited link */
a:link {
  color: red;
}

/* visited link */
a:visited {
  color: green;
}

/* mouse over link */


a:hover {
  color: hotpink;
}

/* selected link */
a:active {
  color: blue;
}
Try it Yourself »

HTML Lists and CSS List Properties


In HTML, there are two main types of lists:

 unordered lists (<ul>) - the list items are marked with bullets
 ordered lists (<ol>) - the list items are marked with numbers or letters

The CSS list properties allow you to:

 Set different list item markers for ordered lists


 Set different list item markers for unordered lists
 Set an image as the list item marker
 Add background colors to lists and list items

Instructional Module created by : Leodivino A. Lawas


Different List Item Markers
The list-style-type property specifies the type of list item marker.

The following example shows some of the available list item markers:

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

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

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

ol.d {
  list-style-type: lower-alpha;
}
Try it Yourself »

CSS Tables
❮ PreviousNext ❯

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

Company Contact

Alfreds Futterkiste Maria Anders

Berglunds snabbköp Christina Berglund

Centro comercial Moctezuma Francisco Chang

Ernst Handel Roland Mendel

Instructional Module created by : Leodivino A. Lawas


Island Trading Helen Bennett

Königlich Essen Philip Cramer

Laughing Bacchus Winecellars Yoshi Tannamuri

Magazzini Alimentari Riuniti Giovanni Rovelli

Try it Yourself »

Table Borders
To specify table borders in CSS, use the border property.

The example below specifies a black border for <table>, <th>, and <td> elements:

Example
table, th, td {
  border: 1px solid black;
}
Try it Yourself »

Full-Width Table
The table above might seem small in some cases. If you need a table that should span
the entire screen (full-width), add width: 100% to the <table> element:

Example
table {
  width: 100%;
}
Try it Yourself »

Double Borders
Notice that the table in the examples above have double borders. This is because both
the table and the <th> and <td> elements have separate borders.
Instructional Module created by : Leodivino A. Lawas
To remove double borders, take a look at the example below.

Collapse Table Borders


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

Example
table {
  border-collapse: collapse;
}
Try it Yourself »

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

Example
table {
  border: 1px solid black;
}
Try it Yourself »

CSS Layout - The
display Property
❮ PreviousNext ❯

The display property is the most important CSS property for controlling layout.

Instructional Module created by : Leodivino A. Lawas


The display Property
The display property specifies if/how an element is displayed.

Every HTML element has a default display value depending on what type of element it
is. The default display value for most elements is block or inline.

Click to show panel

Block-level Elements
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).

The <div> element is a block-level element.

Examples of block-level elements:

 <div>
 <h1> - <h6>
 <p>
 <form>
 <header>
 <footer>
 <section>

Inline Elements
An inline element does not start on a new line and only takes up as much width as
necessary.

This is  an inline <span> element inside  a paragraph.

Examples of inline elements:

 <span>
 <a>

Instructional Module created by : Leodivino A. Lawas


 <img>

Display: none;
display: none; is commonly used with JavaScript to hide and show elements without
deleting and recreating them. Take a look at our last example on this page if you want
to know how this can be achieved.

The <script> element uses display: none; as default. 

Override The Default Display Value


As mentioned, every element has a default display value. However, you can override
this.

Changing an inline element to a block element, or vice versa, can be useful for making
the page look a specific way, and still follow the web standards.

A common example is making inline <li> elements for horizontal menus:

Example
li {
  display: inline;
}
Try it Yourself »

Note: Setting the display property of an element only changes how the element is


displayed, NOT what kind of element it is. So, an inline element with display: block; is
not allowed to have other block elements inside it.

The following example displays <span> elements as block elements:

Example
span {
  display: block;
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »

The following example displays <a> elements as block elements:

Example
a {
  display: block;
}
Try it Yourself »

Hide an Element - display:none or


visibility:hidden?
display:none

Remove
Instructional Module created by : Leodivino A. Lawas
visibility:hidden

Hide

Reset

Instructional Module created by : Leodivino A. Lawas


Reset All

CSS Navigation Bar
❮ PreviousNext ❯

Demo: Navigation Bars


Vertical

 Home
 News
 Contact
 About

Instructional Module created by : Leodivino A. Lawas


Horizontal

 Home
 News
 Contact

 About

 Home
 News
 Contact

 About

Navigation Bars
Having easy-to-use navigation is important for any web site.

With CSS you can transform boring HTML menus into good-looking navigation bars.

Navigation Bar = List of Links


A navigation bar needs standard HTML as a base.

In our examples we will build the navigation bar from a standard HTML list.

A navigation bar is basically a list of links, so using the <ul> and <li> elements makes
perfect sense:

Example
<ul>
  <li><a href="default.asp">Home</a></li>
  <li><a href="news.asp">News</a></li>
  <li><a href="contact.asp">Contact</a></li>
  <li><a href="about.asp">About</a></li>
</ul>

Instructional Module created by : Leodivino A. Lawas


Try it Yourself »

Now let's remove the bullets and the margins and padding from the list:

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

CSS Vertical Navigation Bar


❮ PreviousNext ❯

Vertical Navigation Bar


 Home
 News
 Contact
 About

To build a vertical navigation bar, you can style the <a> elements inside the list, in
addition to the code from the previous page:

Example
li a {
  display: block;
  width: 60px;
}
Try it Yourself »

Example explained:

 display: block; - Displaying the links as block elements makes the whole link area
clickable (not just the text), and it allows us to specify the width (and padding,
margin, height, etc. if you want)
 width: 60px; - Block elements take up the full width available by default. We want
to specify a 60 pixels width
Instructional Module created by : Leodivino A. Lawas
You can also set the width of <ul>, and remove the width of <a>, as they will take up
the full width available when displayed as block elements. This will produce the same
result as our previous example:

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

li a {
  display: block;
}
Try it Yourself »

Vertical Navigation Bar Examples


Create a basic vertical navigation bar with a gray background color and change the
background color of the links when the user moves the mouse over them:

 Home
 News
 Contact
 About

Example
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 200px;
  background-color: #f1f1f1;
}

li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
}

Instructional Module created by : Leodivino A. Lawas


/* Change the link color on hover */
li a:hover {
  background-color: #555;
  color: white;
}
Try it Yourself »

Active/Current Navigation Link


Add an "active" class to the current link to let the user know which page he/she is on:

 Home
 News
 Contact
 About

Example
.active {
  background-color: #04AA6D;
  color: white;
}
Try it Yourself »

Center Links & Add Borders


Add text-align:center to <li> or <a> to center the links.

Add the border property to <ul> add a border around the navbar. If you also want
borders inside the navbar, add a border-bottom to all <li> elements, except for the last
one:

 Home
 News
 Contact
 About

Example
ul {
  border: 1px solid #555;
}

Instructional Module created by : Leodivino A. Lawas


li {
  text-align: center;
  border-bottom: 1px solid #555;
}

li:last-child {
  border-bottom: none;
}
Try it Yourself »

Horizontal Navigation Bar


 Home
 News
 Contact

 About

There are two ways to create a horizontal navigation bar. Using inline or floating list


items.

Inline List Items


One way to build a horizontal navigation bar is to specify the <li> elements as inline, in
addition to the "standard" code from the previous page:

Example
li {
  display: inline;
}
Try it Yourself »

Example explained:

 display: inline; - By default, <li> elements are block elements. Here, we remove
the line breaks before and after each list item, to display them on one line

Floating List Items


Another way of creating a horizontal navigation bar is to float the <li> elements, and
specify a layout for the navigation links:

Instructional Module created by : Leodivino A. Lawas


Example
li {
  float: left;
}

a {
  display: block;
  padding: 8px;
  background-color: #dddddd;
}
Try it Yourself »

Example explained:

 float: left; - Use float to get block elements to float next to each other
 display: block; - Allows us to specify padding (and height, width, margins, etc. if
you want)
 padding: 8px; - Specify some padding between each <a> element, to make them
look good
 background-color: #dddddd; - Add a gray background-color to each <a> element

Tip: Add the background-color to <ul> instead of each <a> element if you want a full-
width background color:

Example
ul {
  background-color: #dddddd;
}
Try it Yourself »

Horizontal Navigation Bar Examples


Create a basic horizontal navigation bar with a dark background color and change the
background color of the links when the user moves the mouse over them:

 Home
 News
 Contact
 About

Instructional Module created by : Leodivino A. Lawas


Example
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* Change the link color to #111 (black) on hover */


li a:hover {
  background-color: #111;
}
Try it Yourself »

Active/Current Navigation Link


Add an "active" class to the current link to let the user know which page he/she is on:

 Home
 News
 Contact
 About

Example
.active {
  background-color: #04AA6D;
}
Try it Yourself »

Instructional Module created by : Leodivino A. Lawas


Right-Align Links
Right-align links by floating the list items to the right ( float:right;):

 Home
 News
 Contact
 About

Example
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li style="float:right"><a class="active" href="#about">About</a></li>
</ul>
Try it Yourself »

Border Dividers
Add the border-right property to <li> to create link dividers:

 Home
 News
 Contact
 About

Example
/* Add a gray right border to all list items, except the last item (last-child)
*/
li {
  border-right: 1px solid #bbb;
}

li:last-child {
  border-right: none;
}

Basic Dropdown
Create a dropdown box that appears when the user moves the mouse over an element.

Instructional Module created by : Leodivino A. Lawas


Example
<style>
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
</style>

<div class="dropdown">
  <span>Mouse over me</span>
  <div class="dropdown-content">
    <p>Hello World!</p>
  </div>
</div>
Try it Yourself »

Example Explained
HTML) Use any element to open the dropdown content, e.g. a <span>, or a <button>
element.

Use a container element (like <div>) to create the dropdown content and add whatever
you want inside of it.

Wrap a <div> element around the elements to position the dropdown content correctly
with CSS.

CSS) The .dropdown class uses position:relative, which is needed when we want the


dropdown content to be placed right below the dropdown button
(using position:absolute).

The .dropdown-content class holds the actual dropdown content. It is hidden by default,


and will be displayed on hover (see below). Note the min-width is set to 160px. Feel free

Instructional Module created by : Leodivino A. Lawas


to change this. Tip: If you want the width of the dropdown content to be as wide as the
dropdown button, set the width to 100% (and overflow:auto to enable scroll on small
screens).

Instead of using a border, we have used the CSS box-shadow property to make the


dropdown menu look like a "card".

The :hover selector is used to show the dropdown menu when the user moves the
mouse over the dropdown button.

ADVERTISEMENT

Dropdown Menu
Create a dropdown menu that allows the user to choose an option from a list:

Dropdown Menu

This example is similar to the previous one, except that we add links inside the
dropdown box and style them to fit a styled dropdown button:

Example
<style>
/* Style The Dropdown Button */
.dropbtn {
  background-color: #4CAF50;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
}

/* The container <div> - needed to position the dropdown content */


.dropdown {
  position: relative;
  display: inline-block;
}

/* Dropdown Content (Hidden by Default) */


.dropdown-content {
  display: none;
Instructional Module created by : Leodivino A. Lawas
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */


.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

/* Change color of dropdown links on hover */


.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu on hover */


.dropdown:hover .dropdown-content {
  display: block;
}

/* Change the background color of the dropdown button when the dropdown content
is shown */
.dropdown:hover .dropbtn {
  background-color: #3e8e41;
}
</style>

<div class="dropdown">
  <button class="dropbtn">Dropdown</button>
  <div class="dropdown-content">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>
Try it Yourself »

Right-aligned Dropdown Content


Left
Right

Instructional Module created by : Leodivino A. Lawas


If you want the dropdown menu to go from right to left, instead of left to right,
add right: 0;

Example
.dropdown-content {
  right: 0;
}

Try it Yourself »

More Examples
Dropdown Image
How to add an image and other content inside the dropdown box.

Hover over the image:

Try it Yourself »

Dropdown Navbar
How to add a dropdown menu inside a navigation bar.

CSS Image Gallery
❮ PreviousNext ❯

CSS can be used to create an image gallery.

Instructional Module created by : Leodivino A. Lawas


Add a description of the image here

Add a description of the image here

Add a description of the image here

Instructional Module created by : Leodivino A. Lawas


Add a description of the image here

Image Gallery
The following image gallery is created with CSS:

Example
<html>
<head>
<style>
div.gallery {
  margin: 5px;
  border: 1px solid #ccc;
  float: left;
  width: 180px;
}

div.gallery:hover {
  border: 1px solid #777;
}

div.gallery img {
  width: 100%;
  height: auto;
}

div.desc {
  padding: 15px;
  text-align: center;
}
Instructional Module created by : Leodivino A. Lawas
</style>
</head>
<body>

<div class="gallery">
  <a target="_blank" href="img_5terre.jpg">
    <img src="img_5terre.jpg" alt="Cinque Terre" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_forest.jpg">
    <img src="img_forest.jpg" alt="Forest" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_lights.jpg">
    <img src="img_lights.jpg" alt="Northern Lights" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

<div class="gallery">
  <a target="_blank" href="img_mountains.jpg">
    <img src="img_mountains.jpg" alt="Mountains" width="600" height="400">
  </a>
  <div class="desc">Add a description of the image here</div>
</div>

</body>
</html>
Try it Yourself »

More Examples
Responsive Image Gallery
How to use CSS media queries to create a responsive image gallery that will look good
on desktops, tablets and smart phones.

Instructional Module created by : Leodivino A. Lawas


Image Sprites - Simple Example
Instead of using three separate images, we use this single image
("img_navsprites.gif"):

With CSS, we can show just the part of the image we need.

In the following example the CSS specifies which part of the "img_navsprites.gif" image
to show:

Example
#home {
  width: 46px;
  height: 44px;
  background: url(img_navsprites.gif) 0 0;
}
Try it Yourself »

Example explained:

 <img id="home" src="img_trans.gif"> - Only defines a small transparent image


because the src attribute cannot be empty. The displayed image will be the
background image we specify in CSS
 width: 46px; height: 44px; - Defines the portion of the image we want to use

Instructional Module created by : Leodivino A. Lawas


 background: url(img_navsprites.gif) 0 0; - Defines the background image
and its position (left 0px, top 0px)

This is the easiest way to use image sprites, now we want to expand it by using links
and hover effects.

Image Sprites - Create a Navigation List


We want to use the sprite image ("img_navsprites.gif") to create a navigation list.

We will use an HTML list, because it can be a link and also supports a background
image:

Example
#navlist {
  position: relative;
}

#navlist li {
  margin: 0;
  padding: 0;
  list-style: none;
  position: absolute;
  top: 0;
}

#navlist li, #navlist a {


  height: 44px;
  display: block;
}

#home {
  left: 0px;
  width: 46px;
  background: url('img_navsprites.gif') 0 0;
}

#prev {
  left: 63px;
  width: 43px;
  background: url('img_navsprites.gif') -47px 0;
}

#next {
Instructional Module created by : Leodivino A. Lawas
  left: 129px;
  width: 43px;
  background: url('img_navsprites.gif') -91px 0;
}
Try it Yourself »

Example explained:

 #navlist {position:relative;} - position is set to relative to allow absolute


positioning inside it
 #navlist li {margin:0;padding:0;list-style:none;position:absolute;top:0;} -
margin and padding are set to 0, list-style is removed, and all list items are
absolute positioned
 #navlist li, #navlist a {height:44px;display:block;} - the height of all the images
are 44px

Now start to position and style for each specific part:

 #home {left:0px;width:46px;} - Positioned all the way to the left, and the width
of the image is 46px
 #home {background:url(img_navsprites.gif) 0 0;} - Defines the background
image and its position (left 0px, top 0px)
 #prev {left:63px;width:43px;} - Positioned 63px to the right (#home width 46px
+ some extra space between items), and the width is 43px.
 #prev {background:url('img_navsprites.gif') -47px 0;} - Defines the background
image 47px to the right (#home width 46px + 1px line divider)
 #next {left:129px;width:43px;}- Positioned 129px to the right (start of #prev is
63px + #prev width 43px + extra space), and the width is 43px.
 #next {background:url('img_navsprites.gif') -91px 0;} - Defines the background
image 91px to the right (#home width 46px + 1px line divider + #prev width
43px + 1px line divider )

Image Sprites - Hover Effect


Now we want to add a hover effect to our navigation list.

Tip: The :hover selector can be used on all elements, not only on links.

Our new image ("img_navsprites_hover.gif") contains three navigation images and


three images to use for hover effects:

Instructional Module created by : Leodivino A. Lawas


Because this is one single image, and not six separate files, there will be no loading
delay when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example
#home a:hover {
  background: url('img_navsprites_hover.gif') 0 -45px;
}

#prev a:hover {
  background: url('img_navsprites_hover.gif') -47px -45px;
}

#next a:hover {
  background: url('img_navsprites_hover.gif') -91px -45px;
}
Try it Yourself »

CSS Attribute Selectors
❮ PreviousNext ❯

Style HTML Elements With Specific


Attributes
It is possible to style HTML elements that have specific attributes or attribute values.

Instructional Module created by : Leodivino A. Lawas


CSS [attribute] Selector
The [attribute] selector is used to select elements with a specified attribute.

The following example selects all <a> elements with a target attribute:

Example
a[target] {
  background-color: yellow;
}
Try it Yourself »

CSS [attribute="value"] Selector


The [attribute="value"] selector is used to select elements with a specified attribute and
value.

The following example selects all <a> elements with a target="_blank" attribute:

Example
a[target="_blank"] {
  background-color: yellow;
}
Try it Yourself »

CSS [attribute~="value"] Selector


The [attribute~="value"] selector is used to select elements with an attribute value
containing a specified word.

The following example selects all elements with a title attribute that contains a space-
separated list of words, one of which is "flower":

Instructional Module created by : Leodivino A. Lawas


Example
[title~="flower"] {
  border: 5px solid yellow;
}

CSS Forms
❮ PreviousNext ❯

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

First Name  Last Name  Country      Australia     Canada     USA    Try it Yourself »

Styling Input Fields


Use the width property to determine the width of the input field:

First Name 

Example
input {
  width: 100%;
}
Try it Yourself »

The example above applies to all <input> elements. If you only want to style a specific
input type, you can use attribute selectors:

 input[type=text] - will only select text fields


 input[type=password] - will only select password fields
 input[type=number] - will only select number fields
 etc..

Instructional Module created by : Leodivino A. Lawas


Padded Inputs
Use the padding property to add space inside the text field.

Tip: When you have many inputs after each other, you might also want to add
some margin, to add more space outside of them:

First Name  Last Name 

Example
input[type=text] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}
Try it Yourself »

Note that we have set the box-sizing property to border-box. This makes sure that the
padding and eventually borders are included in the total width and height of the
elements.
Read more about the box-sizing property in our CSS Box Sizing chapter.

Bordered Inputs
Use the border property to change the border size and color, and use the border-
radius property to add rounded corners:

First Name 

Example
input[type=text] {
  border: 2px solid red;
  border-radius: 4px;
}
Try it Yourself »

If you only want a bottom border, use the border-bottom property:

First Name 

Instructional Module created by : Leodivino A. Lawas


Example
input[type=text] {
  border: none;
  border-bottom: 2px solid red;
}
Try it Yourself »

Colored Inputs
Use the background-color property to add a background color to the input, and
the color property to change the text color:

Example
input[type=text] {
  background-color: #3CBC8D;
  color: white;
}
Try it Yourself »

Focused Inputs
By default, some browsers will add a blue outline around the input when it gets focus
(clicked on). You can remove this behavior by adding outline: none; to the input.

Use the :focus selector to do something with the input field when it gets focus:

Example
input[type=text]:focus {
  background-color: lightblue;
}
Try it Yourself »

Example
input[type=text]:focus {
  border: 3px solid #555;
}
Instructional Module created by : Leodivino A. Lawas
Try it Yourself »

Input with icon/image


If you want an icon inside the input, use the background-image property and position it
with the background-position property. Also notice that we add a large left padding to
reserve the space of the icon:

Example
input[type=text] {
  background-color: white;
  background-image: url('searchicon.png');
  background-position: 10px 10px;
  background-repeat: no-repeat;
  padding-left: 40px;
}
Try it Yourself »

Animated Search Input


In this example we use the CSS transition property to animate the width of the search
input when it gets focus. You will learn more about the transition property later, in
our CSS Transitions chapter.

Example
input[type=text] {
  transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
  width: 100%;
}
Try it Yourself »

Instructional Module created by : Leodivino A. Lawas


Styling Textareas
Tip: Use the resize property to prevent textareas from being resized (disable the
"grabber" in the bottom right corner):

Example
textarea {
  width: 100%;
  height: 150px;
  padding: 12px 20px;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
  background-color: #f8f8f8;
  resize: none;
}
Try it Yourself »

Styling Select Menus


     Australia     Canada     USA   

Example
select {
  width: 100%;
  padding: 16px 20px;
  border: none;
  border-radius: 4px;
  background-color: #f1f1f1;
}
Try it Yourself »

Styling Input Buttons


 

Instructional Module created by : Leodivino A. Lawas


Example
input[type=button], input[type=submit], input[type=reset] {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 4px 2px;
  cursor: pointer;
}

/* Tip: use width: 100% for full-width buttons */


Try it Yourself »

For more information about how to style buttons with CSS, read our CSS Buttons
Tutorial.

Responsive Form
Resize the browser window to see the effect. When the screen is less than 600px wide,
make the two columns stack on top of each other instead of next to each other.

Advanced: The following example use media queries to create a responsive form. You


will learn more about this in a later chapter.

 Try it Yourself »

Chapter 3

JavaScript

4.1 Introduction

• JavaScript is a dynamic language which is used for designing the web pages on the client side.
• It is case sensitive language.
• It is untyped language i.e. a variable can hold any type of value.
• // is used for comments.
• ; i used for line termination.
• JavaScript code should be added at the end i.e. just above the closing-body-tag.
• It is better to write the JavaScript code in separate file as shown in next section.

Instructional Module created by : Leodivino A. Lawas


4.2 First code

The JavaScript code can be written in the ‘html’ file or in the separate ‘JavaScript file (.js)’ as shown in
this
section,

4.2.1 JavaScript in HTML file

In HTML file, the JavaScript codes can be written inside the ‘script’ tag as shown in Lines 11-13 of below
code. The code will write the message “Hello World from JavaScript!” on the web page. Open the
‘js.html’ in the browser to see the message.
<!-- js.html -->

<!DOCTYPE html>
• <html>
<head>
<title>JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World from JavaScript!
<br>"); </script>
</body>
</html>

Below is the output on the HTML page,

Instructional Module created by : Leodivino A. Lawas


Instructional Module created by : Leodivino A. Lawas
Chapter 4. JavaScript

4.2.1.1 JavaScript in separate file

• The JavaScript code is saved in the file ‘my_javascript.js’ which is located inside the folders
‘asset/js’. Notethat, no ‘script tag’ is used here.
// asset/js/my_javascript.js

• document.write("Hello World from JavaScript!<br>");


Next we need to import the .js file in the HTML file as shown below,
<!-- js.html -->

<!DOCTYPE html>
• <html>
<head>
<title>JavaScript</title>
</head>
<body>

<!-- import JavaScript files here -->


<script src="asset/js/my_javascript.js"></script>

</body>
</html>

Now, open the ‘js.html’ file in the browser and it will display the message.

Note: We will use the second method in this tutorial.

4.3 Keywords, Datatypes, Variables and Operators

4.3.1 Keywords

• Below are the reserved keywords in the JavaScript which can not be used as ‘variable’ and
‘function’ names etc.

Table 4.1: List of keywords


Keywor
ds
Instructional Module created by : Leodivino A. Lawas
101
Chapter 4. JavaScript

abstract boolean break byte


case catch char class
const continu debugger default
e
delete do double else
enum export extends false
final float for functio
n
goto if implemen import
ts
in int interface long
native new null packag
e
private protect public return
ed
short static super switch
this throw throws transie
nt
true try typeof var
void volatile while with
4.3.2 Datatypes

JavaScript has three types of data,


• Numbers : 123, 32.32
• Strings : “Meher”, “Krishna Patel”, “123”
• Boolean : true, false

Note: All the numbers are considered as ‘floating point’.

4.3.3 Variables

Variables can be define using keyword ‘var’. Further, JavaScript is untyped language i.e. a variable can
hold any type of value.
• In the below HTML, ‘p’ tag with id ‘p_name’ is defined at Line 10. This id will be used to write
some text using JavaScript,

Instructional Module created by : Leodivino A. Lawas


102
Chapter 4. JavaScript

<!-- js.html -->

• <!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<p id='p_name'></p>
<!-- import JavaScript files here -->
<script src="asset/js/my_javascript.js"></script>

</body>
</html>
Two variables are defined at Lines 9-10 of type ‘string’ and ‘float’ respectively. Then ‘getElementById’
is used to locate the tag with id ‘p_name’ and the text is inserted as shown in Line 11. Lastly, the ‘+’
// asset/js/my_javascript

// print message on the webpage


document.write("Hello World from JavaScript!<br>");

// variable example
var your_name =
"Meher"; var age = 20;
document.getElementById("p_name").innerHTML= "Hello "+ your_name + "<br>Age : " + age;
sign is used to concatenate the values as Line 11.

• Below is the output of above codes. Note that the message ‘Hello World from JavaScript!’ is added at
theend as ‘JavaScript’ file is imported at the end.

Warning: If we import the ‘JavaScript’ file between the ‘ending-head-tag’ and ‘start-body-tag’,
then Message ‘Hello Meher ...’ will not be displayed as ‘JavaScript’ will execute before the loading
of the page; and JavaScript can not find the id ‘p_name’.

Hello Meher
Age : 20

Hello World from JavaScript!

Note: All the JavaScript/HTML codes will be added below the existing codes, therefore only the newly
added code will be shown in the rest of the tutorial.

• ‘prompt’ can be used to read the values from the user.


Instructional Module created by : Leodivino A. Lawas
103
Chapter 4. JavaScript

// prompt
var x = prompt("enter a number"); document.write("2 * ", x, " = ", 2*x +
"<br>");

A pop-up window will appear due to prompt. If we provide the input value as 3, then below output will
be
generated,
2*3=6

Note: The ‘,’ and ‘+’ can be used to combine various outputs as shown in above example

4.3.4 Operators

Various operators are shown in this section. The usage of some of these operators are shown in Section
4.4.

4.3.4.1 Arithmetic operators

• +
• -• *
• /
• % : modulus i.e remainder of the division
• ++ (increment)
• – (decrement)
4.3.4.2 Assignment operators

• =
• +=
• -=
• *=
• /=
• %=

4.3.4.3 Comparison operators

• == (compare only values not type)


• === (compare both values and type)
• !=
• >
• <
• >=
• <=

Instructional Module created by : Leodivino A. Lawas


104
Chapter 4. JavaScript

4.3.4.4 Conditional operator

• ?:
e.g. ‘( (a > b) ? a/b : b/a) )’ i.e if ‘a>b’ then do ‘a/b’ else do ‘b/a’

4.3.4.5 Logical operators

• && (logical and)


• || (logical or)
• ! (logical not)

4.3.4.6 Bitwise operators

• & (and)
• | (or)
• ^ (xor)
• ~ (not)

4.3.5 String to number conversion

‘Number’ is used to convert the string into numbers.


// string to number conversion document.write("2 + Number('3.4') =
", 2 + Number('3.4'), "<br>");

Below is the output of above code,


2 + Number('3.4') = 5.4

4.3.6 Convert to integer

A string or float value can be converted into integer using ‘parseInt’


// int conversion
document.write("2 + parseInt('3.4') = ", 2 + parseInt('3.4'), "<br>"); // string to int document.write("2
+ parseInt(3.4) = ", 2 + parseInt(3.4), "<br>"); // float to int

Below are the outputs of above code,


2 + parseInt('3.4') = 5 2
+ parseInt(3.4) = 5

4.3.7 Convert to float

The ‘parseFloat’ or ‘Number’ can be used to convert the value into float values.
document.write("2 + parseFloat('3.4') = ", 2 + parseFloat("3.4"), "<br>"); // parseFloat
Instructional Module created by : Leodivino A. Lawas
105
Chapter 4. JavaScript

4.3.8 Math

‘Math’ library contains various useful function as shown below,


// math
document.write("pi = ", Math.PI, "<br>");
document.write("e = ", Math.E, "<br>");
document.write("similarly we can use 'abs', 'floor', 'ceil' and 'round' etc. <br>")
document.write("random number : ", Math.ceil(Math.random()*20), "<br>"); // enter random
number
Below are the ouputs of above code,
pi = 3.141592653589793 e = 2.718281828459045
similarly we can use 'abs', 'floor', 'ceil' and 'round' etc.
random number : 16

4.3.9 String

Below are the some of the useful ‘string-styles’,


// string
document.write("meher".toUpperCase(), "<br>") // uppercase

w = "Krishna"
document.write(w.toLowerCase(), "<br>") // lowercase
document.write(w.small(), "<br>") // small
document.write(w.bold(), "<br>") // bold
document.write(w.strike(), "<br>") // strike
document.write(w.fontsize("5em"), "<br>") // strike
document.write(w.link("http://pythondsp.readthedocs.io"), "<br>") // link
document.write(w.fontcolor("red").fontsize("12em"), "<br>") // multiple
The outputs are shown in Fig. 4.1

4.3.10 Arrays

In JavaScript, the arrays can store different types of values as shown in below code,

Instructional Module created by : Leodivino A. Lawas


106
Chapter 4. JavaScript

Fig. 4.1: String styles

// arrays
arr = [15, 30, "Meher"] for(a in
arr) document.write(arr[a], "
");
document.write("<br>");

document.write(arr.pop(), "<br>"); // remove last element


arr.push("Krishna"); // add element to end
document.write(arr.pop(), "<br>");
document.write("lenght of array: ", arr.length, "<br>");
Below are the output of above code,
15 30 Meher
Meher
Krishna lenght of array: 2

4.4 Control structure, loops and functions

4.4.1 If-else

In the below code, three conditions are checked for the variable ‘age’; and corresponding message is
printed.
// asset/js/my_javascript

// if-else age = 10; if (age > 3 && age < 6){ document.write("Age :
" + age + "<b> go to kindergarten</b>");
}
else if ( age >=6 && age < 18){ document.write("Age : " +
Instructional Module created by : Leodivino A. Lawas
107
Chapter 4. JavaScript

age + "<b> go to school</b>");


} else{ document.write("Age : " + age + "<b> go to
college</b>");

}
document.write("<br>");

Instructional Module created by : Leodivino A. Lawas


108
Chapter 4. JavaScript

• Since age is 10, therefore ‘else if’ statement is satisfied and we will get below output,
Age : 10 go to school

4.4.2 Switch-case-default

Below is an example of Switch-case-default statement,


// asset/js/my_javascript

// switch-case
var grade = 'A';
document.write("Grade " + grade + " : ");
switch(grade){ case 'A':
document.write("Very good grade!");
break;
case 'B': document.write("Good
grade!"); break;
default: // if grade is neither 'A' nor 'B'
document.write("Enter correct grade");
}
document.write("<br>
");
• Below is the output of above code,
Grade A : Very good grade!

4.4.3 For loop

Below code prints the value from 5-0,


// For loop for (i=5; i>=0;
i--){ document.write(i + "
");
}
document.write("<br>
");
• Below is the output,
543210

4.4.4 While loop

Below code prints the value from 0-4,


// While loop
x=0; while(x < 5){
document.write(x + " ");
Instructional Module created by : Leodivino A. Lawas
109
Chapter 4. JavaScript

x++; }
document.write("<br
>");
4.4.5 do-while

Below code prints the value from 0-2,


// do-while x=0; do{
document.write(x + " ");
x++; }while(x < 3);
document.write("<br
>");
Below is the output,
012

4.4.6 for-in loop

The ‘for-in’ loop can be used to iterate over the array as shown below,
// for-in loop
arr = [10, 12, 31]; // array for (a
in arr){ document.write(arr[a] +
" ");
}
document.write("<br>
");
4.4.7 Continue and break

Continue and break statements are used inside the ‘loop’ statements.
• Continue will skip the loop and go to next iteration, if the condition is met. In the below code, 3
will not be printed at the output.
// continue for (i=5;
i>=0; i--){ if (i==3){ //
skip 3
continue;
}
document.write(i + " ");
}
document.write("<br>
");
Below is the output where 3 is not printed in the output.
54210

• ‘Break’ statement will quit the loop if the condition is met. In the below code, the for loop will
be terminated at ‘i=3’, therefore only 5 and 4 will be printed,
// break
Instructional Module created by : Leodivino A. Lawas
110
Chapter 4. JavaScript

for (i=5; i>=0; i--){ if (i==3){ // exit


loop when i=3
break;
}
document.write(i + " ");
}
document.write("<br>
");
Below is the output of the above code,

4.4.8 Functions

In the below code a function ‘add2Num’ is defined which adds the two numbers and returns the result.
// function
function add2Num(num1, num2){ // function definition return num1 + num2;
}
sum = add2Num(2, 3); // function call document.write("2 + 3 = " + sum);
document.write("<br>");

Below is the output,


2+3=5

4.5 Event handling

One of the main usage of JavaScript is ‘event handling’. “Mouse click” and ‘pressing keys on keyboard’
are the example of ‘events’. With the help of JavaScript, we can perform certain actions at the
occurrence of the events, as shown below.
• ‘alert’ is used to display message in the ‘pop up’ window.
function alertMessage(message){ alert(message)
}

• In Line 13, message ‘Hello’ is shown in the pop-up window on the event ‘onclick’. Note that
“JavaScript:void(0)” is used here, which does not refresh the page.
• Line 15 is same as Line 13, but “JavaScript:void(0)” is not used, therefore page will be refreshed.
• Line 17 calls the function ‘alertMessage’ to display the mesage, which is defined in the above
code.
• Lines 19-25 use different events i.e. ‘onmouseover’, ‘onmouseleave’, ‘onmouseup’ and
‘onmousedown’; andthe color and the text of the string changes based on these operations.

Instructional Module created by : Leodivino A. Lawas


111
Chapter 4. JavaScript
<!-- js.html -->

<!DOCTYPE html>
4.6 <html> onmouseover="this.style.color='red'",
onmouseleave="this.style.color='blue'",
<head>
onmouseup="this.text='Not
<title>JavaScript</title> clicked'",
onmousedown="this.text='You clicked
</head>
me'"> Not clicked </a><br>
<body>
<!-- import JavaScript files here -->
<p id='p_name'></p>
<script src="asset/js/my_javascript.js"></script>
<a href="JavaScript:void(0)", onclick="alert('Hello')">Say Hello</a><br> <!-- do not reload the page␣
˓→-->
</body>
</html>
<a href="", onclick="alert('Hello')">Say Bye</a><br> <!-- reload the page -->

<a href="JavaScript:void(0)", onclick="alertMessage('Bye via function')">Bye-function</a><br>

<a href="JavaScript:void(0)",
Conclusion

In this tutorial, we have selected the element with certain ‘id’ using ‘getElementById’. Also, we saw the
example of ‘event handling’ Although, we can use JavaScript for these operations, but it is better to use
jQuery for these purposes, which is discussed in Chapter 5. A good approach is use to the jQuery for
‘selectors’ & ‘event handling’ and then use various features of JavaScript which are described in Section
4.4 to implement the logics.

Instructional Module created by : Leodivino A. Lawas


112
Chapter 4

jQuery

5.1 Introduction

jQuery is the Javascipt library.

5.1.1 Requirements

• First create a file ‘jQuery.html’. Next, we need three files, i.e. one CSS (Line 9) and two Javascipt
(Lines 23-24), for using the jQuery in this tutorial. These files are saved inside the folder ‘asset’,
which can be downloaded from the repository. Lines 9 and 24 are the bootstrap files, whereas
Line 23 is the actual ‘jQuery’ file which is required to use the jQuery.

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>

<!-- CSS -->


<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Add Custom styles below -->

</head>
<body>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
<script src="asset/js/bootstrap.min.js"></script>
</body>
</html>

Instructional Module created by : Leodivino A. Lawas


Chapter 5. jQuery

• If we open this html file in the browser, the a blank page will be displayed with header
‘jQuery’.

5.1.2 Add contents

Next add one jumbotron (Line 15-19) and few labels (Lines 21-26) in the html file as shown in
Fig. 5.1.

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>

<!-- CSS -->


<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Add Custom styles below -->

</head>
<body>
<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>

<span class="label label-lg label-default" id="l_default">Default</span>


<span class="label label-primary" id="l_primary">Primary</span>
<span class="label label-success" id="l_success">Success</span>
<span class="label label-info" id="l_info">Info</span>
<span class="label label-warning" id="l_warning">Warning</span>
<span class="label label-danger" id="l_danger">Danger</span>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
<script src="asset/js/bootstrap.min.js"></script>

</body>
</html>

Instructional Module created by : Leodivino A. Lawas


114
Chapter 5. jQuery

Fig. 5.1: Jumbotron and labels are added


5.2 jQuery examples

Following are the important parts for writing a jQuery,


• Selectors : to select the specific element (e.g. ‘id’, ‘class’ etc.) for operations.
• Event handling : perform some operations (hide, toggle etc.) on the selected items at some
events (e.g. click, mouser over etc.).
In this section, we will see the working of of jQuery with the help of some examples. Then in Section 5.3,
we will see various methods to use the selectors to target the specific elements. Next, a list of operations
are shown in Table 5.2. Finally in Section 5.5, a list of events are shown which can be used to initiate the
operations.

5.2.1 Add jQuery code

Now, we can add the jQuery code as shown in Lines 36-40. Please note the following part,
• $ sign is used to hit the jQuery. In the simple words, we can say that it execute the jQuery.
• The code is written between the following block. This block stops the jQuery to execute until the
whole pageis loaded, i.e. jQuery will be executed after completion of the page-download.
$(function() {
// write code here
});
• The above block is a shorthand for below,
$(document).ready(function() { // write code here
});

Note: We can use multiple blocks, if we want to separate the codes; or we can write all the jQueries
within one block.

• Lastly, the below line hides the id “l_default” after 1000 ms, i.e. ‘Default’ label will not be
displayed after
1000 ms as shown in Fig. 5.2
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
Instructional Module created by : Leodivino A. Lawas
115
Chapter 5. jQuery

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>

<!-- CSS -->


<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Add Custom styles below -->

</head>
<body>

<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>

<span class="label label-lg label-default" id="l_default">Default</span>


<span class="label label-primary" id="l_primary">Primary</span>
<span class="label label-success" id="l_success">Success</span>
<span class="label label-info" id="l_info">Info</span>
<span class="label label-warning" id="l_warning">Warning</span>
<span class="label label-danger" id="l_danger">Danger</span>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
<script src="asset/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
});
</script>
</body>
</html>

Fig. 5.2: Label ‘Default’ is hidden after 1000 ms


Instructional Module created by : Leodivino A. Lawas
116
Chapter 5. jQuery

Note: ‘#” is used to select the ‘id’; whereas ‘.’ is sued to access the ‘class’.

• In the below code, the label ‘Danger’ is removed; and “opacity=‘0.5’” is set for rest of the labels.
Here, ‘.label’ selects all the classes which have the name ‘label’ in it. Since all the entries have
classes with name ‘label’, therefore all are selected and faded according to ‘opacity=‘0.5’, as
shown in Fig. 5.3.

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>

<!-- CSS -->


<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Add Custom styles below -->

</head>
<body>

<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>

<span class="label label-lg label-default" id="l_default">Default</span>


<span class="label label-primary" id="l_primary">Primary</span>
<span
<span class="label
class="label label-info" id="l_info">Info</span>
label-success" id="l_success">Success</span>
<span class="label label-warning" id="l_warning">Warning</span>
<span class="label label-danger" id="l_danger">Danger</span>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
<script src="asset/js/bootstrap.min.js"></script>

<script type="text/javascript">
$(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").hide(); // hide class = 'label' using . operator
Instructional$(".label").css({opacity:'0.5'});
Module created by : Leodivino // A.
addLawas
opacity to all classes with name 'label'
});
117
</script>
</body>
</html>
Chapter 5. jQuery

Fig. 5.3: Faded labels

5.2.2 jQuery in separate file

It is better to write the jQuery in the separate files, therefore the codes are more manageable.
• For this, first write the code in the separate file ‘my_jquery.js’ as below,

Note: ‘html’ is used to change the content of the ‘id’ as shown in Line 5 below listing (see Fig.
5.4)

// asset/js/my_jquery.js

$(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").html("Shark is dangerous"); // change content using 'html'
});

Next, import this file to ‘html’ as shown in Line 35 of below code,

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
</head>
<head>
<body>
<title>jQuery</title>

<!--<div
CSSclass="jumbotron">
-->
<div class="col-md-offset-4 container">
<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<h1><b>jQuery</b></h1>
<!-- Add Custom styles below -->
</div>
</div>

<span class="label label-lg label-default" id="l_default">Default</span>


<span class="label label-primary" id="l_primary">Primary</span>
<span class="label label-success" id="l_success">Success</span>
<span class="label label-info" id="l_info">Info</span>
<span class="label label-warning" id="l_warning">Warning</span>
<span class="label label-danger" id="l_danger">Danger</span>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
Instructional Module created by : Leodivino A. Lawas
<script src="asset/js/bootstrap.min.js"></script>
<script src="asset/js/my_jquery.js"></script> 118
</body>
</html>
Chapter 5. jQuery

Fig. 5.4: Changed content using ‘html’ option

5.2.3 Get input from user

Below is the complete html code, which we will use in this section,

Listing 5.1: complete HTML code

<!-- jQuery.html -->

<!DOCTYPE html>
<html>
<head>
<title>jQuery</title>

<!-- CSS -->


<link href="asset/css/bootstrap.min.css" rel="stylesheet">
<!-- Add Custom styles below -->

</head>
<body>

<div class="jumbotron">
<div class="col-md-offset-4 container">
<h1><b>jQuery</b></h1>
</div>
</div>

Instructional Module created by : Leodivino A. Lawas


119
5.2. jQuery examples

(continued from previous page)


<span class="label label-lg label-default" id="l_default">Default</span>
<span class="label label-primary" id="l_primary">Primary</span>
<span class="label label-success" id="l_success">Success</span>
<span class="label label-info" id="l_info">Info</span>
<span class="label label-warning"
id="l_warning">Warning</span> <span class="label label-
danger" id="l_danger">Danger</span>

<br><br>
<span class="btn btn-sm btn-warning" id="b_warning">Toggle Warning Label</span>

<br><br>
<!-- label_id is custom attribute whouse values are set according to id of above labels-->
<span class="btn btn-sm btn-default label-btn" label_id='l_default'>Toggle Default Label</span>
<span class="btn btn-sm btn-primary label-btn" label_id='l_primary'>Toggle Primary
Label</span>
<span class="btn btn-sm btn-success label-btn" label_id='l_success'>Toggle Success
Label</span>
<span class="btn btn-sm btn-info label-btn" label_id='l_info'>Toggle Info Label</span>
<span class="btn btn-sm btn-warning label-btn" label_id='l_warning'>Toggle Warning
Label</span>
<span class="btn btn-sm btn-danger label-btn" label_id='l_danger'>Toggle Danger Label</span>

<!-- Javascript -->


<!-- put jQuery.js before bootstrap.min.js; and then add custom jquery-->
<script src="asset/js/jquery-3.3.1.min.js"></script>
<script src="asset/js/bootstrap.min.js"></script>
<script src="asset/js/my_jquery.js"></script>

</body>
</html>
5.2.3.1 Toggle label on mouse click

In this section, the ‘mouse click’ on the button ‘Toggle Warning Label (Line 29)’ is read; and then the
label ‘warning’ is toggled.
• The method ‘on’ waits for user’s input ‘click (i.e. mouse click)’.
• On mouse-click next query i.e. ‘toggle’ is executed which hides/unhide the ‘warning label’ as shown
in Fig.
5.5 - Fig. 5.6.

Instructional Module created by : Leodivino A. Lawas


120
Chapter 5. jQuery

// asset/js/my_jquery.js

// 'hide label' and 'change content' $


(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").html("Shark is dangerous"); // change content using 'html'
});
// toggle 'warning label' based on click on the button 'Toggle Warning Label' $
(function() {
$('#b_warning').on('click', function(){ $('#l_warning').toggle();
});
});

5.2.3.2 Toggle label based on the buttons

In previous section, we wrote the code which can toggle only one label. In this section, we will toggle
multiple labels by writing one-generalized-jQuery as shown in Fig. 5.7.

Fig. 5.5: Hide label ‘warning’

Fig. 5.6: Show label ‘warning’

• Lines 21-26 and 31-38 of Listing 5.1 are used for this section,
• Custom attributes “label_id=...” are added in each button which has the value which
corresponds to oneof the ‘label’s id’. e.g. ‘label_id’ for Line 33 (i.e. l_default) is same as ‘id’ at
Line 21.
• Next, in the below jQuery, we saved the ‘label_id’ in a variable (see Line 21) and then the
variable is usedto toggle the labels.

Listing 5.2: Toggle the label based on the button-clicked

Instructional Module created by : Leodivino A. Lawas


121
Chapter 5. jQuery

// asset/js/my_jquery.js

// 'hide label' and 'change content' $


(function() {
$("#l_default").hide(1000); // hide id = 'l_default' using # operator after 300 ms
$(".label-danger").html("Shark is dangerous"); // change content using 'html'
});

// toggle 'warning label' based on click on the button 'Toggle Warning Label' $
(function() {
$('#b_warning').on('click', function(){ $('#l_warning').toggle();
});
});
// toggle panels according to the clicked-buttons
$(function(){
$('.label-btn').on('click', function(){ // select class 'label-btn' var labelId = $
(this).attr('label_id'); // store the attribute value of 'label_id'
(continues on next page)

Fig. 5.7: Toggle labels based on button-clicked

$('#' + labelId).toggle(); // toggle the label with id stored in 'label_id'


});
});
(continued from previous page)

5.3 Selectors

In this section, we will use following HTML to understand the various combination of the selectors which
are summarized in Table 5.1,
<!DOCTYPE html>
<html>
<head>
<title>jQuery Selectors</title>
</head>
<body>

Instructional Module created by : Leodivino A. Lawas


122
Chapter 5. jQuery

<p>jQuery Selectors</p>

<p class="foo"> Paragraph with class.</p>


<p><span>Paragraph with span.</span></p>

<p id="bar">Paragraph with ID. <span class="foo">Span with class and inside the paragraph-
with-id.</
˓→span></p>

<div>
<p my-id="my_para">Paragraph (with custom id) inside the div</p>
<p my-id="my_para2"><span>Span inside the paragraph (with custom id) inside the
div</span></p>
</div>

<!-- Javascript -->


<script src="asset/js/jquery-3.3.1.min.js"></script>

</body>
</html>

Note:
• Press ‘ctrl+shift+k’ (or go to Tools->Web Developer->Web Console) to open the web-console in
Firefox and click on ‘console’ and type the ‘jQuery’ commands there.
• Press ‘ctrl+shift+J’ (or go to Tools->Javascript Console) in ‘Chrome’ and type the jQuery
commands there.
• In this tutorial, the output of the ‘Firefox’ are shown.

5.3.1 Select elements

5.3.1.1 Select HTML elements

HTML elements, e.g. div, p, span and table etc., can be selected by writing them with the quotation mark
as shown in below codes.
• Here, ‘$(‘p’) is the command, whereas the lines below it are the outputs.
• The outputs show the ‘selected elements’; and the total number of selected elements i.e.
‘length: 6’.
• If we put the cursor to one of the outputs, then it will highlight the corresponding elements in
the html asshown in Fig. 5.8.

Instructional Module created by : Leodivino A. Lawas


123
Chapter 5. jQuery

$('p') {...}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-
id="my_para"> 5: <p
my-id="my_para2">
length: 6

Fig. 5.8: Output of $(‘p’); (see red-squares)

• Similarly, we can select ‘div’ elements


$('div') {...}
0: <div>
length: 1

5.3.1.2 Select class

Class can be selected using ‘.’ operator. In below code, class ‘foo’ is selected.
$(".foo")
{...}
0: <p class="foo"> 1: <span class="foo"> length: 2

5.3.1.3 Select ID

ID can be selected using ‘#’ operator. In the below code, id ‘bar’ is selected.
$('#bar')
[...]
0: <p id="bar"> length: 1

5.3.1.4 Combining selectors

Instructional Module created by : Leodivino A. Lawas


124
Chapter 5. jQuery

We can select a element with specific class name using ‘.’ operator as shown in below code. Here
element ‘span’ with class ‘foo’ is selected,
$("span.foo")
{...}
0: <span class="foo"> length: 1

5.3.1.5 Multiple selectors

Use ‘,’ to select different types of elements. In the below code, “paragraph with id ‘bar’” and “elements
with class ‘foo’” are selected ,
$('p#bar, .foo')
{...}
0: <p class="foo">
1: <p id="bar"> 2: <span class="foo"> length: 3

5.3.1.6 Select descendant element

Select ‘span’ inside the ‘p’ (use space between ‘span’ and ‘p’),
$('p span')
{...}
0: <span>
1: <span class="foo">
2: <span>
length: 3
5.3.1.7 Select child element

The ‘>’ is used to select the child of an element.


$
('div>span')
{...} length:
0

Note: There is one element inside ‘div’ but it’s path is ‘div->p->span’ therefore ‘span’ is a child of ‘p’ (not
of ‘div’). But tgis ‘span’ is the descendant of ‘div’ therefore can be accessed using space,
$('div span')
{...}
0: <span> length: 1

5.3.1.8 Attribute selector


Instructional Module created by : Leodivino A. Lawas
125
Chapter 5. jQuery

Custom attributes can be selected as below,


$('[my-id = my_para]') {...}
0: <p my-id="my_para">
length: 1

$('p[my-id != my_para]') // select p with 'my-id != my_para'


{...}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar"> 4: <p
my-id="my_para2">
length: 5

$('p[class = foo]')
{...}
0: <p class="foo">
length: 1
5.3.2 Filters

Various filter options (e.g. filter, first, last and has etc.) can be used after ‘:’ as shown below,
$('p:first') // select first element
{...}
0: p

$('p:last') // last element


{...}
0: <p my-id="my_para2">
length: 1

$('p:not(.foo)') // 'p' which does not have class 'foo'


{...}
0: <p>
1: <p>
2: <p id="bar">
3: <p my-
id="my_para"> 4: <p
my-id="my_para2">
length: 5

$('p:has(span)') // 'p' which has 'span' inside it


{...}
0: <p>
1: <p id="bar"> 2: <p
Instructional Module created by : Leodivino A. Lawas
126
Chapter 5. jQuery

my-id="my_para2">
length: 3

$('p:hidden') // hidden 'p'


{...} length:
0

$('p:visible') // visible 'p'


{...}
0: <p>
1: <p class="foo">
2: <p>
3: <p id="bar">
4: <p my-
id="my_para"> 5: <p
my-id="my_para2">
length: 6

$('p:contains(with class)') // paragraph which contains class inside it

{...}
0: <p class="foo">
1: <p id="bar">
length: 2

$('p').filter(".foo") // same as p.foo


{...}
0: <p class="foo">
length: 1

$('p').not(".foo") // p with not class foo


{...}
0: <p>
1: <p>
2: <p id="bar">
3: <p my-
id="my_para"> 4: <p
my-id="my_para2">
length: 5

$('p').last() // last element of 'p'


{...}
0: <p my-id="my_para2">
length: 1

$('p').has('span') // p with span


{...}
Instructional Module created by : Leodivino A. Lawas
127
Chapter 5. jQuery

0: <p>
1: <p id="bar"> 2: <p
my-id="my_para2">
length: 3

$('p').is('.foo') // does 'p' contain 'foo' true

$('p').children() // children of 'p'


{...}
0: <span>
1: <span class="foo">
2: <span>
length: 3

$('p').children(".foo") // child of 'p' with class 'foo'


{...}
0: <span class="foo">
length: 1

Table 5.1: Selectors

Command Description example


$(‘elementName’) select the tags (p, body, table) $(‘p’), $(‘body’)
$(‘.className’) select element with ‘className’ $(“.foo”)
$(‘elementName.className’) element with className $(“span.foo”)
$(selector1, selector2) select selector1 and selector2 $(‘p#bar, .foo’)
$(selector1 selector2) select selector2 inside selector1 $(‘p span’)
$(selector1>selector2) select selector2 which is child of $(‘div>span’)
selector1
5.4 Operations
$(attributName = select attribute with someName $(‘[my-id =
In someName)
Listing 5.2 we saw some operations e.g. ‘hide()’ and ‘toggle()’. Table 5.2my_para]’)
shows some more such
$p(attributName = select ‘p’ with attribute with
operations. Table 5.2: Operations $(‘p[my-id =
someName) Operations someName my_para]’)

hide() hide(speed fadeIn(speed) fadeOut(speed)


)
show() show(spee slideDown(spe slideToggle(spe
d) ed) ed)
slideUp(spee toggle() toggle(speed) toggle(switch)
d)
5.5 Event handling

In Listing 5.2 we saw one example of event handling, where certain operations are performed on the
event ‘mouse click’. Table 5.2 shows a list of some more events.
Instructional Module created by : Leodivino A. Lawas
128
Chapter 5. jQuery

Table 5.3: Event handle


Events

click keydown keypre keyu


ss p
mousedo mouseov
wn er

Web References:

https://www.w3schools.com/
https://devdocs.io/
https://www.freecodecamp.org/news/
https://developer.mozilla.org/en-US/docs/Web
https://tympanus.net/codrops/css_reference/
https://stackoverflow.com/

Related Wrox Books:

Beginning CSS: Cascading Style Sheets for Web Design, 2nd Edition
ISBN: 978-0-470-09697-0
This comprehensive introduction clearly shows you how to combine Cascading Style Sheets (CSS) with
HTML, XHTML, or XML to create rich, aesthetically compelling web designs. Packed with detailed
Instructional Module created by : Leodivino A. Lawas
129
Chapter 5. jQuery

examples in syntax-colored code and showing the resulting web pages in color, the second edition will
help you discover how and why CSS works.

Beginning JavaScript, 4th Edition


ISBN: 978-0-470-52593-7
Serving as a great introduction to JavaScript, this book offers all you need to start using JavaScript on
your web pages right away. It’s fully updated and covers utilizing JavaScript with the latest versions of
the Internet Explorer, Firefox, and Safari browsers and walks you through the basics of JavaScript: what it
is, how it works, and what you can do with it.

Beginning JavaScript and CSS Development with jQuery


ISBN: 978-0-470-22779-4
With this unique, project-oriented book, author Richard York teaches even the most novice of JavaScript
users how to quickly get started utilizing the JavaScript jQuery Library to decrease the amount of code
that needs to be written and tested. A four-color code syntax highlighting system provides a visual
reinforcement and allows you to see the nuts and bolts that comprise each line and section of code. With
this helpful guide and hands-on exercises, you’ll be able to put jQuery to work for you and avoid having
to write code from scratch.

Instructional Module created by : Leodivino A. Lawas


130

You might also like