Html5 and Css3 Learn HTML and Css From Experts Web Development Crash Course
Html5 and Css3 Learn HTML and Css From Experts Web Development Crash Course
Neo D. Truman
Copyright
COPYRIGHT
TABLE OF CONTENTS
PREFACE
Book Audience
How to Contact Us
Acknowledgments
Conventions Used in This Book
SETTING UP A DEVELOPMENT ENVIRONMENT
1.1 Install a Code Editor
1.1.1 Install Essential Extensions
1.1.2 Install Live Server
1.1.3 Setting Default Formatter
1.1.4 Enable Formatting Code on Save
1.1.5 Auto Save Files on Focus Change
1.1.6 Disable Compact Folders
1.1.7 Enable Word Wrap
1.1.8 Set Tab Size Smaller
1.2 Using a Web Browser
1.2.1 Using Developer Tools in The Browser
1.2.2 Using Console Tool
1.2.3 Using Source Tool
1.3 Preparing a Workspace
PART I: HTML5
What will you learn?
CHAPTER 1 GETTING TO KNOW HTML
1.1 Two Types of HTML Elements
1.2 HTML Document Structure
1.3 Your First Webpage
1.4 Character Encoding
1.5 Element Attributes
1.6 Favorite Icon
1.7 Comments
CHAPTER 2 HTML ELEMENTS
2.1 Headings
2.2 Paragraphs
2.3 Hyperlinks
2.3.1 External Anchors
2.3.2 Internal Anchors
2.3.3 Download Links
2.4 Images
2.4.1 Image Maps
2.4.2 Responsive Pictures
2.5 Lists
2.5.1 Unordered List
2.5.2 Ordered List
2.5.3 Description Lists
2.6 Tables
2.6.1 Table Headers
2.6.2 Table Rows
2.6.3 Table Caption
2.6.4 Group of Columns
2.6.5 Column Span
2.7 Breaks
2.7.1 Line Breaking
2.7.2 Thematic Breaking
2.8 Progress Bars
2.8.1 <progress>
2.8.2 <meter>
2.9 Computer Code
2.9.1 <code>
2.9.2 <pre>
2.10 Iframes
2.11 HTML Entities
CHAPTER 3 HTML STYLES
3.1 Formatting Elements
3.1.1 <b>
3.1.2 <i>
3.1.3 <u> or <ins>
3.1.4 <s> or <del>
3.1.5 <mark>
3.1.6 <sub> and <sup>
3.2 HTML Style Attribute
CHAPTER 4 SEMANTIC HTML
4.1 Semantic Elements
4.1.1 <blockquote>
4.1.2 <address>
4.1.3 <details> and <summary>
4.1.4 <figure> and <figcaption>
4.2 Semantic Layout Elements
4.3 Semantic Formatting Elements
4.3.1 <strong>
4.3.2 <em>
How to Contact Us
Please email contact@neodtruman.com to ask questions about this
book.
Follow us on the Amazon Author page, https://www.amazon.com/Neo-
D-Truman/e/B09P6LHL2M, for news and information about our books.
Acknowledgments
First, I must thank my parents for their love and guidance. Thank you,
parents, for buying me my first computer, which started my career path.
Then, I want to express this special thanks to my dear wife. My wife
takes care of everything in the family. Thanks to that, I have time to
contribute to the community and complete this book.
Finally, my sincere thanks are to my loved ones in my family, friends,
colleagues, and people who have supported and helped me.
Conventions Used in This Book
The following conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file
extensions.
Bold
Indicates important concepts or UI items, such as menu items and
buttons to be selected or clicked.
Constant width
Indicates computer code, including statements, functions, classes,
objects, methods, properties, etc.
You must manually refresh your web page only once after
waking up your PC.
We can undock it into a separate window or only change the dock side
following these steps:
● Click the “Customize and control Dev Tools” button in the upper-
right-hand corner.
● Then select the dock side you want, as shown in the picture below.
You can see the errors on your web page and the debugging messages
here. The Console panel is the one that shows the messages you output with
console.log() and any unhandled errors.
● Select menu File > Save to save the change to the index.html file.
● Hover the mouse on the EXAMPLE folder and click the New File
icon.
● Type “style.css” and press Enter but leave the file empty.
● Select menu File > Save to save the change to the style.css file.
While learning this book, you will change the HTML code
in the index.html file and the CSS code in the style.css file.
Let's try the code in a web browser like Google Chrome. Before
following the steps, you should configure Google Chrome as your default
web browser.
Right-click the index.html file from Explorer Window and click
on Open with Live Server.
It will launch a local web server with a live reload feature for the file
index.html.
We could change our HTML code and save the index.html file.
Consequently, the web page will load the change for us, as shown in this
screenshot.
Part I: HTML5
The above structure is always the same in all web pages, where the
<head> element is for things that are not visible in the browser as it will
contain the page title, some metadata of the page, links to CSS files, etc.
On the other hand, all the visible elements are placed inside the
<body> element so that they will appear on the web pages. We often link
our JavaScript files at the end of the <body> tag.
3 Your First Webpage
Let’s add two more elements. The first element is the <title> element,
which is used to set the webpage’s title and is shown in the browser’s title
tab. The second one is the <h1> element, which is the main heading for
the webpage, so we should only use it once.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome to my site!</h1>
</body>
</html>
The UTF-8 character set covers almost all of the characters and symbols
in the world. Naturally, therefore, we should use it on our web pages.
5 Element Attributes
Various HTML elements have different attributes to configure the
elements, set their contents, or adjust their behavior.
For example, we use the “ lang ” attribute to specify the language of our
web pages as below.
<html lang="en">
6 Favorite Icon
A favorite icon is a small image displayed to the left of the page title in
the browser tab, like this:
Do these steps to add a favorite icon to your website:
● prepare an ICO file as your favorite icon (A common name for it is
“favicon.ico,” but not mandatory)
● save the file in the root directory or its sub-folder
● finally, add a <link> element to your “index.html” file, like the
below example.
Example
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="icon" type="image/x-icon" href="/images/favicon.ico" />
</head>
<body>
<h1>Welcome to my site!</h1>
</body>
</html>
If the favorite icon were placed inside the root folder, the
<link> element would change its href attribute as below.
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
7 Comments
Comments are used to explain code and to make it more readable. They
can also be used to prevent execution when testing alternative code.
In HTML, we use “ <!-- ” and “ --> ” to comment out code by wrapping
the code by them as in the below example.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Heading 1</h1>
<!-- <h2>Heading 2</h2>
<h3>Heading 3</h3> -->
</body>
</html>
1 Headings
There are six headings from <h1> to <h6>, as “h” stands for
“heading.” The <h1> tag is the most important heading and has the biggest
font size. In contrast, <h6> defines the least important heading and is the
smallest one.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
</body>
</html>
It can be seen on the “index.html” page that there are six headings in
different sizes.
2 Paragraphs
We use <p> elements to create paragraphs since “p” stands for
“paragraph.”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Heading 1</h1>
<p>This is your first paragraph.</p>
</body>
</html>
3 Hyperlinks
The hyperlink is one of the fundamental HTML elements. A hyperlink
(or “link” for short) contains an URL attribute so that links can help users
navigate through a website. Without links, visitors do not know how to go
to other web pages since they do not know their addresses.
To create a link, we use the <a> element which stands for “anchor.”
The content between the opening and closing tags is the text displayed on
the webpage.
/contact.html
<!DOCTYPE html>
<html>
<head>
<title>Contact Page</title>
</head>
<body>
<h1>This is Contact Page</h1>
<a href="/">Home Page</a>
</body>
</html>
/user/login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>This is Login Page</h1>
<a href="/">Home Page</a>
</body>
</html>
Now, users can navigate between the “Home” page, the “Contact” page,
and the “Login” page using those links. Since index.html is the main page,
we can write “ / ” instead of “ /index.html .”
To open an URL in a new tab, we can specify the “ target ” attribute as
“ _blank .”
/index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Home Page</h1>
<a href="/contact.html" target="_blank">Contact Page</a>
<a href="/user/login.html">Login Page</a>
</body>
</html>
Moreover, we can set the “ href ” attribute to an URL of another
website, such as “https://www.google.com.”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Home Page</h1>
<a href="#cake">Go to My Cake</a>
● the alternative text will be used when the “ src ” attribute is invalid.
Because the path is invalid, the browser cannot download the image,
so that it will display the image description from the “ alt ” attribute.
<img src="invalid-image.pg" alt="This is an apple" />
Two more attributes are usually used in the <img> element; they are
“ width ” and “ height .” However, we only use one to scale the image up or
down. Otherwise, using both will distort the image because our width and
height may not be in the same ratio as the original image size.
Let’s examine a square image of 300x300 pixels.
● This code will scale down the image:
or
<img src="my-image.jpg" alt="This is an apple" height="100" />
or
<img src="my-image.jpg" alt="This is an apple" height="500" />
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<img src="navbar.jpg" alt="Navigation bar" usemap="#nav-bar" width="160" height="80"
/>
<map name="nav-bar">
<area shape="rect" coords="20,20,80,60" alt="Computer" href="#cake" />
<area shape="circle" coords="120,40,20" alt="Coffee" href="#apple" />
</map>
Result:
HTML
is the standard markup language for Web pages.
CSS
is the language we use to style an HTML document.
JavaScript
is the world's most popular programming language.
6 Tables
When arranging data into rows and columns, we use the <table>
elements. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid black;
}
.days {
background-color: lightyellow;
}
.weekend {
background-color: lightblue;
}
</style>
</head>
<body>
<table>
<caption>
September 2022
</caption>
<colgroup>
<col span="5" class="days" />
<col span="2" class="weekend" />
</colgroup>
<thead>
<tr>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
</tr>
<tr>
<td>12</td>
<td>13</td>
<td>14</td>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
</tr>
<tr>
<td>19</td>
<td>20</td>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
</tr>
<tr>
<td>26</td>
<td>27</td>
<td>28</td>
<td>29</td>
<td>30</td>
<td colspan="2"></td>
</tr>
</tbody>
</table>
</body>
</html>
Result:
.6.1 Table Headers
In the above example, a table header is a <tr> element that contains
some <th> elements. Moreover, we often put this <tr> element inside a
<thead> element. Table headers are optional.
Result:
.8.2 <meter>
The <meter> element defines a scalar measurement within a known
range, such as dish usage. The “ value ” attribute is the current meter’s
value, while the “ max ” attribute is the maximum value of the meter. For
example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>
Disk usage:
<meter value="60" max="120"></meter>
60GB of 120GB
</p>
</body>
</html>
Result:
9 Computer Code
.9.1 <code>
The <code> element defines computer code. It will be displayed in the
default monospace font of the browser. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>This is a piece of JavaScript code:</p>
<code>var x = 10;</code>
</body>
</html>
.9.2 <pre>
Text in a <pre> element is displayed in the browser’s default
monospace font. Moreover, the text will be displayed as written in the
HTML code. It means that both spaces and line breaks will be kept
unchanged. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<pre>
Text in a pre element is displayed
in the browser’s default monospace font,
and it preserves both spaces
and line breaks
</pre>
</body>
</html>
10 Iframes
An <iframe> element displays another webpage within the current
HTML document. Its “ src ” attribute sets the URL to be loaded into the
iframe. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
#my-iframe {
width: 800px;
height: 600px;
border: none;
}
</style>
</head>
<body>
<h1>Web Development Books</h1>
<iframe id="my-iframe" src="https://www.amazon.com/dp/B09VFLS7TF"></iframe>
</body>
</html>
or
&#entity-number;
Below is an example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<footer>© 2022, Neo D. Truman</footer>
</body>
</html>
CHAPTER 3
HTML Styles
1 Formatting Elements
.1.1 <b>
We can make some text in bold by putting it inside a <b> element as
“b” stands for “bold.” For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>This is your <b>first paragraph</b></p>
</body>
</html>
The text “first paragraph” will turn bold when we reload the webpage.
.1.2 <i>
Besides, we can wrap some text that we want to be italic inside of the
<i> element as “i” stands for “italic.” For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>This is your <i>first paragraph</i></p>
</body>
</html>
.1.5 <mark>
The <mark> element defines the text that should be highlighted by
changing its background color. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>This is an <mark>important</mark> paragraph</p>
</body>
</html>
1 Semantic Elements
.1.1 <blockquote>
The <blockquote> element specifies a quoted portion from another
website or source. URL of the source is defined using the “ cite ” attribute.
For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>Here is a quote from Wikipedia:</p>
<blockquote cite="https://en.wikipedia.org/wiki/HTML">The HyperText Markup Language or
HTML is the standard markup language for documents designed to be displayed in a web
browser.</blockquote>
</body>
</html>
.1.2 <address>
To define the contact information of the author of a document or an
article, we use the <address> element. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<address>
<p>12345 South St. Philadelphia, PA 12345</p>
<p>
<a href="tel:123-456-7890">123-456-7890</a><br />
<a href="mailto:contact@neodtruman.com">contact@neodtruman.com</a>
</p>
</address>
</body>
</html>
.1.3 <details> and <summary>
The <details> element is used to create a widget that users can open
and close (it is closed by default). When opened, it shows the content
within.
The <summary> element is a child of <details> and defines the
heading for the details. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<details>
<summary>HTML</summary>
<p>HTML is the standard markup language for Web pages.</p>
</details>
</body>
</html>
.1.4 <figure> and <figcaption>
A <figure> element defines a photo in the HTML documents. Besides,
we often use the <figcaption> element to add a caption for it. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<figure>
<img src="an-apple.jpg" alt="An apple" />
<figcaption>Fig.1 - My apple</figcaption>
</figure>
</body>
</html>
2 Semantic Layout Elements
HTML has several semantic elements that define different portions of a
webpage. They are:
● <article> element defines independent content.
● <main> element specifies the main content of the HTML document.
<main>
<section>
<h2>Section's Heading 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eget ex eget lacus luctus
porta ac ut nisi. Nunc euismod maximus faucibus. In hac habitasse platea dictumst. Sed molestie
consequat massa, non sollicitudin metus dapibus eu.</p>
</section>
<section>
<h2>Section's Heading 2</h2>
<p>In egestas dictum suscipit. Vestibulum condimentum tristique imperdiet. Quisque lacinia
eros et tempus volutpat. Morbi malesuada eleifend sapien, id tristique urna porta maximus.</p>
</section>
</main>
<footer>
<p>Copyright © 2022 by Neo D. Truman</p>
<address>
<p>12345 South St. Philadelphia, PA 12345</p>
<p>
<a href="tel:123-456-7890">123-456-7890</a><br />
<a href="mailto:contact@neodtruman.com">contact@neodtruman.com</a>
</p>
</address>
</footer>
</body>
</html>
.3.2 <em>
The <em> element emphasizes a piece of content since it stands for
“emphasize.” For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Heading 1</h1>
<p>This is your <em>first paragraph</em></p>
</body>
</html>
CHAPTER 5
Web Forms
We use HTML forms to collect user input and send it to our server for
processing. A web form might contain many HTML input elements to
collect the user input. Each input usually has a label describing what
information the user should enter.
Below is a simple form that we usually see on web pages:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<form action="/login">
<label for="acc-name">Username:</label>
<input type="text" id="acc-name" name="username" /><br />
<label for="acc-pass">Password:</label>
<input type="password" id="acc-pass" name="password" /><br />
<input type="submit" value="Log in" />
</form>
</body>
</html>
Result:
Enter some text into the boxes and click the “Log in” button, and you
will be redirected to the “/login” page. For example, I entered “ john ” as
my username and “ 123 ” as my password, so I have been redirected to this
URL:
http://127.0.0.1:5500/login?username=john&password=123
It also means that the browser has sent an HTTP request to the web
server to retrieve the webpage at the address “http://127.0.0.1:5500/login,”
including a query string, which in this case is
“ username=john&password=123 .” In the query string, “ username ” and
“ password ” are specified by the “ name ” attributes of the <input>
elements. Finally, the server will authenticate users using this username and
password.
1 HTML Form Elements
.1.1 <input> and <label>
The <input> element is used to collect user input. There are many
types of inputs, and they will be introduced in the next section.
Besides, a <label> element is often used to describe what information
the user should enter into the <input> tag. The “ for ” attribute of <label>
specifies which form element this label is bound to by using the element’s
ID. As a result, the input will get focused when the user clicks on the label.
Example:
<label for="fname">First name:</label>
<input type="text" id="fname" name="firstname" />
Result:
.1.2 <textarea>
The <textarea> element defines a multi-line text input control.
Example:
<textarea name="comment" rows="3" cols="30"> </textarea>
Result:
Users can enter as many lines of text as they want into the element.
Moreover, they can drag and drop the bottom-right corner of the
<textarea> element to resize it.
.1.3 <select> and <option>
The <select> element is used to create a drop-down list containing
many options. Each option is defined by using an <option> element.
Example:
<select name="car">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Result:
Result:
.1.4 <button>
The <button> element defines a clickable button. The button’s text is
placed between the opening and closing tags. When a user clicks a
<button> element inside a form ( <form> ), all form values will be
submitted to the server.
Example:
<button>Submit</button>
Result:
Result:
.1.6 <datalist>
The <datalist> element specifies a list of pre-defined options for an
<input> element.
Example:
<datalist id="car-list">
<option value="Volvo"></option>
<option value="Saab"></option>
<option value="Mercedes"></option>
<option value="Audi"></option>
</datalist>
<input type="text" name="car" list="car-list" />
Result:
2 HTML Input Types
.2.1 Buttons
.2.1.1 button
The <input type="button"> element is a clickable button. Its “ value ”
attribute is used to set the button’s text.
This input type needs the “ onclick ” attribute to specify which
JavaScript code will be executed when the user clicks the button. Without
the attribute, this input type will do nothing when the user clicks it.
Example:
<input type="button" value="Click me" onclick="alert('Hi')" />
Result:
.2.1.2 submit
The <input type="submit"> element is a submit button that submits all
form values to the server. Its “ value ” attribute is used to set the button’s
text, but it is optional since its default value is “ Submit .”
Example:
<input type="submit" />
Result:
.2.1.3 reset
The <input type="reset"> element is a reset button that resets all form
values to their initial values. Its “ value ” attribute is used to set the button’s
text, but it is optional since its default value is “ Reset .”
Example:
<input type="reset" />
Result:
.2.1.4 image
The <input type="image"> element is an image used as a submit
button. This special button also submits the coordinates where the user
clicks on the button, for example:
http://127.0.0.1:5500/login?firstname=John&x=36&y=25
Example: (please prepare the “ btn-submit.jpg ” image by yourself)
<input type="image" src="btn-submit.jpg" alt="Submit" width="50" height="50" />
.2.2 Texts
.2.2.1 text
The <input type="text"> defines a single-line text field.
Example:
<input type="text" name="firstname" />
When we type “John” into the input field, we will see this:
.2.2.2 password
The <input type="password"> defines a password field.
Example:
<input type="password" name="password" />
When we type “ 12345678 ,” into the input field, we will see this:
The input’s value is still “ 12345678 ” but the browser hides it since this
input is a password field.
.2.2.3 email
The <input type="email"> defines a field for an email address.
Example:
<input type="email" name="email" />
This email input differs from the text input since it has a simple email
validation. When a user clicks the submit button, the browser will validate
the user input whether is a valid email or not. For example:
.2.2.4 url
The <input type="url"> defines a field for entering a URL.
Example:
<input type="url" name="yourSite" />
This URL input differs from the text input since it has a simple URL
validation. When a user clicks the submit button, the browser will validate
user input whether it is a valid URL or not. For example:
.2.2.5 hidden
The <input type="hidden"> defines a hidden input field. Although it is
not displayed on the webpage, its value will be submitted to the web server
when the user clicks the submit button.
Example:
<input type="hidden" name="userId" value="123" />
.2.3 Numbers
.2.3.1 number
The <input type="number"> defines a field for entering a number, so
the user can only enter numbers.
The “ min ” and “ max ” attributes are optional. We use them to tell the
browser to validate user input before submitting it to the server.
Example:
<input type="number" name="quantity" min="1" max="9" />
Result:
.2.3.2 range
The <input type="range"> defines a control for selecting a number via
slider control.
Example:
<input type="range" name="points" min="0" max="10" />
Result:
.2.4 Options
.2.4.1 checkbox
The <input type="checkbox"> elements support selecting one or more
options.
Example:
<input type="checkbox" id="book" name="book" value="Book" />
<label for="book"> I have a book</label>
<br />
<input type="checkbox" id="pen" name="pen" value="Pen" />
<label for="pen"> I have a pen</label>
Result:
.2.4.2 radio
The <input type="radio"> are radio buttons usually presented in
several related options. Only one radio button in a group can be selected
simultaneously.
So, in this example, we can select only one option:
<input type="radio" id="book" name="schoolThing" value="Book" />
<label for="book"> A book</label>
<br />
<input type="radio" id="pen" name="schoolThing" value="Pen" />
<label for="pen"> A pen</label>
Result:
.2.5 Files
The <input type="file"> element defines a file-select field and a
“Choose File” button for file uploads.
Example:
<input type="file" name="bgimage" />
Result:
.2.6 Date and Time
.2.6.1 date
The <input type="date"> element defines a date picker.
Example:
<input type="date" name="birthday" />
Result:
.2.6.2 time
The <input type="time"> element defines a time picker.
Example:
<input type="time" name="alarmTime" />
Result:
.2.6.3 datetime-local
The <input type="datetime-local"> element defines a date-time picker.
Example:
<input type="datetime-local" name="alarmDateTime" />
Result:
.2.7 Colors
The <input type="color"> element defines a color picker.
Example:
<input type="color" name="bgcolor" />
Result:
3 HTML Input Attributes
.3.1 name
The most important attribute of an HTML form element is “ name ”
since it will be used as a parameter in the query string, which will be sent to
the web server when the user submits the form. We have already known
how it works at the beginning of this chapter.
.3.2 value
The “ value ” attribute defines an initial value for an input element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<form action="/login">
<label for="fname">First name:</label>
<input type="text" id="fname" name="firstname" value="John" />
</form>
</body>
</html>
Result:
.3.3 placeholder
The “ placeholder ” attribute specifies a short hint describing an input
element’s expected value. The hint will be replaced with user input as they
type.
This attribute works with <input> (input types: text, password, email ,
and url ) and <textarea> .
Example:
<input type="text" name="firstname" placeholder="Your first name here" />
Result:
.3.4 readonly
The “ readonly ” attribute is used to make an element un-editable.
.3.5 disabled
The “ disabled ” attribute makes an element unusable and un-clickable.
This attribute can be applied to these elements: <input>, <button>,
<textarea>, <select>, <option>, <optgroup> , and <fieldset> .
Result:
.3.6 size
The “ size ” attribute specifies the width of an <input> element in
characters. For <select> elements, the “ size ” attribute specifies the
number of visible options in its drop-down list.
Example:
<input type="text" name="firstname" size="6" />
Result:
.3.7 multiple
The “ multiple ” attributes specify that users can enter more than one
value in the <input> (input types: email and file ) or <select> elements.
Example:
<select name="cars" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Result:
.3.8 step
The “ step ” attribute specifies the interval between legal numbers in an
<input> element. For example, if the step is 2, valid numbers could be -2,
0, 2, 4, 6, etc. This attribute is often applied to this input type: number .
Example:
<input type="number" name="points" step="2" />
Result:
.3.10 autofocus
The autofocus attribute specifies that an element should get focused
when the page loads. This attribute can be applied to these elements:
<input>, <textarea>, <select> , and <button> .
Example:
<input type="text" name="fname" autofocus />
.3.11 autocomplete
The autocomplete attribute allows the browsers to:
● predict the value when users start typing into an input field
● and display options to fill in the field based on earlier user input.
It works with <form> and these input types: text, password, email ,
and url .
Example:
<input type="text" name="fname" autocomplete />
4 Form Validation
.4.1 minlength
The minlength attribute specifies the minimum number of characters
required in an input field. This attribute works with <input> (input types:
text, password, email , and url ) and <textarea> .
Example:
<input type="text" name="username" minlength="6" />
Result:
.4.2 maxlength
The maxlength attribute specifies the maximum number of characters
allowed in an input field. This attribute works with <input> (input types:
text, password, email , and url ) and <textarea> .
Example:
<input type="text" name="username" maxlength="6" />
In the above example, users cannot enter the 7th character into the input.
.4.4 required
The required attribute specifies that an input field must be entered as a
value before submitting the form. This attribute works with these elements:
<input>, <textarea> , and <select> .
Result:
.4.5 pattern
The pattern attribute specifies a regular expression that the element's
value will be checked against on form submission. This attribute works with
these input types: text, password, email , and url .
The “ title ” attribute of the input will be used as a hint when validation
fails.
Result:
CHAPTER 6
HTML Multimedia
1 Audio
We use the <audio> elements to embed audio files into our webpage.
These are supported audio formats: MP3, WAV, and OGG but MP3 is
recommended since almost browsers support it.
Attributes of the <audio> element:
● controls - shows the control panel (play/pause, timeline, and
volume)
● autoplay - plays the audio right after the page loaded
● preload - the audio file should be loaded when the page loads. The
preload attribute is ignored if autoplay is present
● src - specifies the location (URL) of the audio file
Example 2:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<audio controls autoplay loop src="my-music.mp3"></audio>
</body>
</html>
Result:
2 Video
We use the <video> elements to embedded video files into our
webpage. These are supported video formats: MP4, WebM, and Ogg, but
MP4 is recommended since almost browsers support it.
Attributes of the <video> element:
● controls - shows the control panel (play/pause, timeline, and
volume)
● autoplay - plays the audio right after the page loaded
● muted – no sound mode
Example 2:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<video width="320" height="240" autoplay>
<source src="my-video.mp4" type="video/mp4" />
<source src="my-video.ogg" type="video/ogg" />
This browser does not support the video element.
</video>
</body>
</html>
CHAPTER 7
HTML Graphics
1 SVG Graphics
SVG stands for Scalable Vector Graphics and defines graphics for the
web. SVG images are zoomed or resized without losing quality, often used
as icons on web pages. Moreover, SVG files are pure XML, so they can be
compressed before transferring via the internet.
We use <svg> element to define an SVG image. The “ width ” and
“ height ” attributes determine the image’s width and height. This element
often has several children elements to define/draw the picture, like the
below example having a <line> element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<svg width="100" height="100">
<line x1="0" y1="0" x2="100" y2="50" stroke="red" stroke-width="2" />
</svg>
</body>
</html>
Result:
Result:
Result:
.1.3 SVG Ellipse
We use the <ellipse> element to draw an ellipse in an SVG image or a
<svg> tag. Its center will be at point ( cx, cy ), and the “ rx ” attribute
defines its horizontal radius; the “ ry ” attribute defines its vertical radius.
Example:
<svg width="100" height="100">
<ellipse cx="50" cy="50" rx="40" ry="20" fill="yellow" stroke="red" stroke-width="2" />
</svg>
Result:
.1.4 SVG Line
We use the <line> element to draw a line in an SVG image or a <svg>
tag. The line will start from a point ( x1, y1 ) and be drawn to a point ( x2,
y2 ). Finally, we must specify the stroke color using the “ stroke ” attribute;
nothing will be drawn without it!
Example:
<svg width="100" height="100">
<line x1="0" y1="0" x2="100" y2="50" stroke="red" stroke-width="2" />
</svg>
Result:
Result:
.1.6 SVG Polygon
The <polygon> element works like an auto “closed” <polyline> . It
means that a line will automatically connect the final point to the first point.
Example:
<svg width="100" height="100">
<polygon points="50,0 100,50 50,100 0,50" fill="white" stroke="red" stroke-width="2" />
</svg>
Result:
Result:
Explanation:
● M50 0 - move the pen to point P1(x1, y1) = (50, 0)
● L25 80 - draw a line from the previous point ( P1 ) to the point
P2(x2, y2) = (25, 80)
● l50 0 - draw a line from the previous point ( P2 ) to the point P3(x2
+ 50, y2 + 0) = (25 + 50, 80 + 0) = (75, 80)
● Z – draw a line from the previous point ( P3 ) to the first point
( P1 )
.1.8 SVG Text
The <text> element defines a text.
Example:
<svg height="100" width="200">
<text x="0" y="20" fill="red">This is a line of text.</text>
</svg>
Result:
Example:
<svg width="100" height="100">
<line x1="10" y1="10" x2="90" y2="10" stroke="red" stroke-width="6" />
<line x1="10" y1="30" x2="90" y2="30" stroke="red" stroke-width="6" stroke-linecap="butt"
/>
<line x1="10" y1="50" x2="90" y2="50" stroke="red" stroke-width="6" stroke-
linecap="square" />
<line x1="10" y1="70" x2="90" y2="70" stroke="red" stroke-width="6" stroke-
linecap="round" />
</svg>
Result:
In the above example, square and round endings make the line longer
than its actual length, more than 80px.
Result:
Explanation:
● 10 was used to draw the 1st line segment
● 5 was used to make the 1st space
● 20 was used to draw the 2nd line segment
since the line is 300px in length, it continues to use the dash array to
draw the rest
● 10 was used to make the 2nd space
● 5 was used to draw the 3rd line segment
● 20 was used to make the 3rd space
and
● 10 was used to draw the 4th line segment
● 5 was used to make the 4th space
● 20 was used to draw the 5th line segment
and so on.
Result:
Example 2:
<svg height="100" width="200">
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="yellow" />
<stop offset="50%" stop-color="green" />
<stop offset="100%" stop-color="red" />
</linearGradient>
</defs>
<rect x="0" y="0" width="200" height="100" fill="url(#grad)" />
</svg>
Result:
Result:
.1.12 SVG Filters
The <filter> element defines an SVG filter. There are many filters
available in SVG, but we will only examine the Gaussian Blur, the
<feGaussianBlur> element, in the example below.
The “ stdDeviation ” attribute of <feGaussianBlur> defines the amount
of the blur, and the in="SourceGraphic" specifies that the effect is for the
entire element.
Example:
<svg height="100" width="200">
<defs>
<filter id="my-filter">
<feGaussianBlur in="SourceGraphic" stdDeviation="30" />
</filter>
</defs>
<rect x="0" y="0" width="200" height="100" fill="green" filter="url(#my-filter)" />
</svg>
Result:
2 Canvas
The <canvas> element is used to draw graphics on a webpage via
JavaScript. Therefore, it always has an “ id ” attribute to be later referred to
by JavaScript code. Besides, the “ width ” and “ height ” attributes define
the canvas size.
By default, the canvas has no border and a transparent background so
that we can place it in front of another element, such as a video, and draw
rectangles to mark things like cars on the road, for example.
Example:
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
Result:
Finally, we use the drawing object to draw text on our canvas using the
fillText() method. We can also set a font for the text using the “ font ”
property.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
ctx.font = "20px Arial";
ctx.fillText("Neo D. Truman", 10, 50);
</script>
</body>
</html>
Result:
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
</body>
</html>
Result:
Since we want to draw a circle, the start angle is set to 0 and the end
angle to 2*PI.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>
</body>
</html>
Result:
.2.4 Draw Rectangles
We also get the drawing object from our canvas to draw a rectangle.
Then use these two methods to draw it:
● rect(x,y,width,height) - draw a rectangle with the top-left corner at
point ( x,y ) and width and height as specified
● stroke() - invoke the drawing
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
ctx.rect(20, 20, 160, 60);
ctx.stroke();
</script>
</body>
</html>
Result:
.2.5 Draw Gradients
7.2.5.1 Linear Gradient
We use the createLinearGradient(x1,y1,x2,y2) method to create a
linear gradient where ( x1,y1 ) and ( x2,y2 ) define the start and end
position of the gradient. Besides, the addColorStop() method specifies a
color stop along the gradient; its value can be anywhere between 0 to 1.
Finally, we use the “ fillStyle ” property to specify the gradient to be
filled in the shape.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0, 0, 200, 0);
grd.addColorStop(0, "red");
grd.addColorStop(1, "yellow");
// Fill with gradient
ctx.fillStyle = grd;
Result:
7.2.5.2 Radial Gradient
We use the createRadialGradient( x1,y1,r1,x2,y2,r2 ) method to create
a radial gradient where ( x1,y1 ) is the center and r1 is the radius of the
innermost circle; the ( x2,y2 ) is the center, and r2 is the radius of the
outermost circle. Besides, the addColorStop() method specifies a color
stop along the gradient; its value can be anywhere between 0 to 1.
Finally, we use the “ fillStyle ” property to specify the gradient to be
filled in the shape.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<canvas id="my-canvas" width="200" height="100" style="border: 1px solid #ccc"> This
browser does not support the canvas tag. </canvas>
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(60, 60, 10, 95, 50, 70);
grd.addColorStop(0, "red");
grd.addColorStop(1, "yellow");
// Fill with gradient
ctx.fillStyle = grd;
Result:
<script>
var c = document.getElementById("my-canvas");
var ctx = c.getContext("2d");
function drawMyImage() {
// At point (50,0), draw the image at its intrinsic size 150x150
ctx.drawImage(this, 50, 0);
Result:
CHAPTER 8
HTML Advanced
1 Data URIs
Data URI (Uniform Resource Identifier) supports including inline data
in web pages as if they were external resources. Below is the syntax of a
data URI:
data:[<media type>][;base64],<data>
Where:
● <media type> - (optional) is a MIME type string having this format:
type/subtype;parameter=value . For example, if it is omitted, the
default value is “ text/plain;charset=US-ASCII ”
● ;base64 - (optional) specifies that the data is base64-encoded binary
data, so it is used with media types like images.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<textarea name="input" cols="30">Change this text and click the download link</textarea>
<script type="text/javascript">
var input = document.querySelector("textarea[ name = 'input' ]");
var download = document.querySelector("a[ download ]");
function updateDownloadHref() {
var text = input.value;
// Build the Data URI
download.setAttribute("href", "data:text/plain;charset=utf-8," +
encodeURIComponent(text));
}
</script>
</body>
</html>
Result:
2 Block Elements
Block elements occupy 100% of the parent element’s width, regardless
of content. Therefore, they are stacked vertically by default.
These elements could have more space than their contents by using
these CSS properties: width, height, padding, and margin .
These are HTML block elements: body, header, nav, main, section,
footer, h1-h6, p, div, ul, ol, li, pre, blockquote, address, details, figure,
fieldset , etc.
We can change other types of elements to block elements using this CSS
declaration:
display: block
3 Inline Elements
Inline elements only occupy the space necessary for their contents so
that they will not cause any line breaks. Therefore, they could not use these
CSS properties: width, height, padding-top, padding-bottom, margin-top,
margin-bottom .
These are HTML inline elements: formatting elements ( b, strong, i, em,
mark, etc.), label, a, span, code, img, button , etc.
We can change other types of elements to inline elements using this CSS
declaration:
display: inline
4 Inline-block Elements
The inline-block elements have both characteristics of inline and block
elements. They only occupy the space necessary for their contents so that
they will not cause any line breaks. However, they could have more space
than their contents by using these CSS properties: width, height, padding,
and margin .
These are HTML inline-block elements: button, input, textarea, select,
progress, meter, iframe, img, svg, canvas, audio, video , etc.
We can change other types of elements to inline-block elements using
this CSS declaration:
display: inline-block
CHAPTER 9
HTML Events
1 Window Events
.1.1 onload
The “ onload ” attribute fired when the browser finished loading a
webpage. We usually handle the “ onload ” event on these elements:
<body>, <iframe>, <img>, <link> , and <script> .
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script>
function eventHandler() {
alert("Page is loaded");
}
</script>
</head>
<body onload="eventHandler()">
<h1>This is a heading</h1>
</body>
</html>
.1.2 onresize
The “ onresize ” attribute fires when the browser window is resized.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script>
function eventHandler() {
alert("You have changed the size of your browser window!");
}
</script>
</head>
<body onresize="eventHandler()">
<h1>This is a heading</h1>
</body>
</html>
2 Form Events
.2.1 onfocus
The “ onfocus ” attribute fires when the element gets focused.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
First name: <input type="text" onfocus="eventHandler(this)" />
<script>
function eventHandler(input) {
input.style.background = "yellow";
}
</script>
</body>
</html>
.2.2 onblur
The “ onblur ” attribute fires when the element loses focus.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
Enter your name: <input type="text" id="fname" onblur="eventHandler()" />
<script>
function eventHandler() {
var x = document.getElementById("fname");
alert("Hi " + x.value);
}
</script>
</body>
</html>
.2.3 onchange
The “ onchange ” attribute fires when the element’s value has been
changed. Supported HTML tags: <input type="checkbox">, <input
type="file">, <input type="password">, <input type="radio">, <input
type="range">, <input type="text">, <select> and <textarea> .
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<select id="my-select" onchange="eventHandler()">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<script>
function eventHandler() {
var x = document.getElementById("my-select").value;
alert("You selected: " + x);
}
</script>
</body>
</html>
.2.4 oninput
The “ oninput ” attribute fires when an element gets user input.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>Write some text into the box!</p>
<p id="output"></p>
<script>
function eventHandler() {
var x = document.getElementById("my-input").value;
document.getElementById("output").innerHTML = "You wrote: " + x;
}
</script>
</body>
</html>
3 Keyboard Events
.3.1 onkeydown
The “ onkeydown ” attribute fires when users press a key on the
keyboard.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>A function is triggered when the user presses a key in the input field.</p>
<script>
function eventHandler() {
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
.3.2 onkeyup
The “ onkeyup ” attribute fires when the users release a key on the
keyboard.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>A function is triggered when the user releases a key in the input field. This function
transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="eventHandler()" />
<script>
function eventHandler() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
.3.3 onkeypress
The “ onkeypress ” attribute fires when users press a key on the
keyboard.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>A function is triggered when the user presses a key in the input field.</p>
<script>
function eventHandler() {
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
4 Mouse Events
.4.1 onclick
The “ onclick ” attribute fires on a mouse click on the element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<button onclick="eventHandler()">Click me</button>
<script>
function eventHandler() {
alert("You clicked the button");
}
</script>
</body>
</html>
.4.2 ondblclick
The “ ondblclick ” attribute fires on a mouse double-click on the
element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<button ondblclick="eventHandler()">Click me</button>
<script>
function eventHandler() {
alert("You double-clicked the button");
}
</script>
</body>
</html>
.4.3 onmousemove
The “ onmousemove ” attribute fires when the pointer is moving while it
is over an element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p onmousemove="enlarge(this)">The function enlarge() is triggered when the user mouse
pointer is moved over the paragraph. This function will enlarge the font size.</p>
<script>
function enlarge(x) {
var oldFontSize = x.style["font-size"];
if (!oldFontSize) {
oldFontSize = 16;
} else {
oldFontSize = parseFloat(oldFontSize.replace("px", ""));
}
<script>
function mouseDown() {
document.getElementById("p1").style.color = "red";
}
function mouseUp() {
document.getElementById("p1").style.color = "blue";
}
</script>
</body>
</html>
.4.5 onmouseover and onmouseout
The “ onmouseover ” attribute fires when the mouse pointer moves over
an element. On the other hand, the “ onmouseout ” attribute fires when the
mouse pointer moves out of an element.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p onmouseover="increaseFontSize(this)" onmouseout="decreaseFontSize(this)">
When the user mouse over the paragraph, its font size will be 32px. <br />
When the mouse pointer is moved out of it, the font size will be 20px.
</p>
<script>
function increaseFontSize(x) {
x.style["font-size"] = "32px";
}
function decreaseFontSize(x) {
x.style["font-size"] = "20px";
}
</script>
</body>
</html>
5 Clipboard Events
.5.1 oncopy
The “ oncopy ” attribute fires when the user copies the content of an
element. There are two ways to copy the content:
● Press CTRL + C
● Right-click to display the context menu and select the "Copy"
command
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<input type="text" oncopy="eventHandler()" value="Try to copy this text" />
<script>
function eventHandler() {
alert("You copied the text.");
}
</script>
</body>
</html>
.5.2 oncut
The “ oncut ” attribute fires when the user cuts the content of an
element. There are two ways to cut the content:
● Press CTRL + X
<script>
function eventHandler() {
alert("You cut the text.");
}
</script>
</body>
</html>
.5.3 onpaste
The “ onpaste ” attribute fires when the user pastes some content in an
element. There are two ways to paste some content into an element:
● Press CTRL + V
<script>
function eventHandler() {
alert("You pasted the text.");
}
</script>
</body>
</html>
CHAPTER 10
HTML APIs
Then, specify what happens when the element is dragged using the
“ ondragstart ” attribute. Finally, we will define a callback function for it to
invoke when users start dragging. In this function, we will call the
dataTransfer.setData() method to set the dragged data.
<div id="div1" draggable="true" ondragstart="dragStartHandler(event)">This div is
draggable</div>
<script>
function dragStartHandler(evt) {
evt.dataTransfer.setData("sourceID", evt.target.id);
}
</script>
<script>
function allowDropping(evt) {
evt.preventDefault();
}
</script>
<script>
function dropHandler(ev) {
var data = ev.dataTransfer.getData("sourceID");
ev.target.appendChild(document.getElementById(data));
}
</script>
<script>
function allowDropping(ev) {
ev.preventDefault();
}
function dropHandler(ev) {
var data = ev.dataTransfer.getData("sourceID");
ev.target.appendChild(document.getElementById(data));
}
function dragStartHandler(ev) {
console.log(ev);
ev.dataTransfer.setData("sourceID", ev.target.id);
}
</script>
</body>
</html>
0.2 Geolocation
The HTML Geolocation API in JavaScript helps us get the user’s
geographical position (latitude and longitude). By default, the position is
unavailable unless the user approves it because this can compromise
privacy.
We use geolocation.getCurrentPosition() method of the navigator
object to get the user’s current position. The function receives a callback as
its parameter to return a coordinate object to the callback.
Example:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>Click the button to get your coordinates.</p>
<p id="out"></p>
<script>
var x = document.getElementById("out");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " +
position.coords.longitude;
}
</script>
</body>
</html>
0.3 Web Storage
Before HTML5, application data had to be stored in cookies which
would be included in every server request. Consequently, using cookies
affects our website performance.
Our web applications can store data locally within the browsers with
web storage. Web storage is more secure, large amounts of data (at least
5MB) can be stored locally, and it is never transferred to the server.
Before using web storage, we should check browser support for it:
if (typeof Storage !== "undefined") {
// Code for Web Storage
} else {
// Not support Web Storage
}
HTML web storage provides two objects for storing data on the client:
● localStorage - stores data with no expiration date
● sessionStorage - stores data for one session (data is lost when the
browser tab is closed)
// Retrieve
var firstname = localStorage.getItem("firstname");
// Retrieve
var firstname = localStorage.firstname;
The syntax for removing the “firstname” item in the local storage is as
follows:
localStorage.removeItem("firstname");
<p>Step 4. Click this button to get data from the Local Storage:</p>
<input type="button" value="Get data" onclick="getItem()" />
<p>Step 5. Close all tabs and open this page again. Then, click the "Get data" button to see if
we can still get the data.</p>
<script>
function setItem() {
if (typeof Storage !== "undefined") {
var name = document.getElementById("name").value;
localStorage.myName = name;
}
}
function getItem() {
if (typeof Storage !== "undefined") {
alert(localStorage.myName);
}
}
</script>
</body>
</html>
<p>Step 3. Click this button to get data from the Session Storage:</p>
<input type="button" value="Get data" onclick="getItem()" />
<p>Step 5. Then, click the "Get data" button to see that we cannot get the data since it's only
available in the first tab.</p>
<script>
function setItem() {
if (typeof Storage !== "undefined") {
var name = document.getElementById("name").value;
sessionStorage.myName = name;
}
}
function getItem() {
if (typeof Storage !== "undefined") {
alert(sessionStorage.myName);
}
}
</script>
</body>
</html>
0.4 Web Workers
The page becomes unresponsive when executing JavaScript code on a
webpage until the execution is finished. Therefore, when we have
JavaScript code that could run for a long time, we put it in a Web Worker.
A Web Worker is a JavaScript code running in the background without
blocking users from doing whatever they want on the webpage, such as
clicking, selecting things, etc.
function startCounter() {
i = i + 1;
postMessage(i);
setTimeout("startCounter()", 1000);
}
startCounter();
The most critical line of the above code is the postMessage() method
which is used to post a message back to our HTML page.
When the web worker posts a message, the code within the event
listener is executed. The data from the web worker is stored in event.data .
Finally, to terminate a web worker and free the resources of the browser,
we use the terminate() method and set the variable to undefined :
w.terminate();
w = undefined;
<script>
var w;
function startWorker() {
if (typeof Worker !== "undefined") {
if (typeof w == "undefined") {
w = new Worker("my-web-worker.js");
}
w.onmessage = function (event) {
document.getElementById("result").innerHTML = event.data;
};
} else {
document.getElementById("result").innerHTML = "This browser does not support Web
Workers!";
}
}
function stopWorker() {
w.terminate();
w = undefined;
}
</script>
</body>
</html>
0.4.3 Web Workers and the DOM
Since web workers are placed in external JavaScript files and run in
other threads, they do not have access to the following JavaScript objects of
the DOM:
● The window object
While talking about CSS3, we must mention its predecessor, CSS. CSS is
an acronym for Cascading Style Sheets, the language used to style web
pages.
Why should we learn CSS3?
CSS3 is the 3rd and the latest version of CSS. CSS3 has added many
more convenient features for users than CSS. Inheriting everything from the
previous version and adding new features, CSS3 is now very popular in
website design.
CSS is a tool that helps us add changes in appearance, such as changing
layout, colors, fonts, etc. If a web page does not have CSS, it will simply be
a page containing text with two primary colors, black and white.
CSS works by partitioning the selection based on the HTML tag name,
ID, or class. From there, apply the properties to be changed to the selected
HTML elements.
What will you learn?
In this part of the book, you will learn the following:
● Basic CSS: CSS syntax, comments, and units (absolute and relative
lengths).
● Three types of CSS: Inline CSS, Internal CSS, and External CSS.
CSS stands for Cascading Style Sheets. It describes the visual style and the
presentation of the HTML content in a web browser. It can also change a
site’s display based on different screen sizes and devices. In addition, CSS
includes rules that format the content, such as font, text, layout, etc.
In this book, we will learn CSS3 since it is the latest version of CSS.
CSS3 has added many more convenient features for users than CSS.
Inheriting everything from the previous version and adding new features,
CSS3 is now very popular in website design. However, I will write “CSS”
as a shorthand for “CSS3” from now on.
.1 CSS Syntax
Let’s examine this example:
p{
color: red;
font-size: 28px;
}
.2 Comments in CSS
Any code should have comments to maintain the code later easily. The
comments start with “ /* ” and end with “ */ .” Web browsers will ignore all
comments.
Example:
/* Single Line */
/*
Multiple
Lines
*/
.3 CSS Units
CSS code has several different units for expressing a length. In addition,
some CSS properties take length values, such as width, margin, padding,
font-size, border-width , etc. A length is a number followed by a length unit,
for example, 10px or 2em .
A whitespace cannot appear between the number and the unit. However,
if the value is 0 , the unit can be omitted. Moreover, some CSS properties
can have negative lengths.
● mm : millimeters
style.css
article {
font-size: 20px;
}
.custom {
font-size: 1.5em;
}
style.css
.parent {
font-size: 15px;
}
.child {
font-size: 2em;
}
style.css
.parent {
font-size: 15px;
}
.child {
font-size: 2rem;
}
Example 2:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="parent">
I'm 1.5rem = 1.5 * 10px = 15px
<div class="child">
I'm 2.6rem = 2.6 * 10px = 26px, as expected
<div class="child">I'm 26px, good!</div>
</div>
</div>
</body>
</html>
style.css
html {
/* font-size: 10px; */
font-size: 62.5%;
}
.parent {
font-size: 1.5rem;
}
.child {
font-size: 2.6rem;
}
style.css
div {
height: 50px;
border-color: red;
border-style: solid;
border-top-width: 5px;
border-right-width: 10px;
border-bottom-width: 15px;
border-left-width: 20px;
}
Example 2:
div {
border-width: 5px 10px 15px;
}
equals
div {
border-top-width: 5px;
border-right-width: 10px;
border-bottom-width: 15px;
border-left-width: 10px; /* = border-right-width */
}
Example 3:
div {
border-width: 5px 10px;
}
equals
div {
border-top-width: 5px;
border-right-width: 10px;
border-bottom-width: 5px; /* = border-top-width */
border-left-width: 10px; /* = border-right-width */
}
Example 4:
div {
border-width: 5px;
}
equals
div {
border-top-width: 5px;
border-right-width: 5px;
border-bottom-width: 5px;
border-left-width: 5px;
}
.5 Where Do We Put Our CSS?
1.5.1 Inline CSS
Inline CSS code is put in the HTML elements’ style attribute. The
styles are applied only to the elements that declare the “ style ” attribute.
In the below example, inline styles are applied only to the first
paragraph since the second <p> element does not have any “ style ”
attribute.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p style="color: red; font-size: 26px">This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
It is not practical since we could have many lines of CSS code. In this
case, that CSS code would pollute the HTML file and makes both CSS and
HTML code hard to maintain.
1.5.3 External CSS
External CSS is in an external CSS file (*.css) as below. Then, we need
to tell the HTML file that we want to use that external CSS file by using the
<link> element inside the <head> element. The <link> element has two
attributes:
● rel : relationship of the linked document to the current document, so
we set it to “ stylesheet ”
● href : this attribute specifies the URL of the linked resource
style.css
p{
color: red;
font-size: 28px;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
We can put the internal and external CSS anywhere inside the HTML
file, but why should we put them inside the <head> element? Let’s try this
example to see the reason.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<link rel="stylesheet" href="style.css" />
</body>
</html>
● Then, they are changed to big red texts when the CSS file is
loaded.
It is not a good user experience since users see two styles of content
and a flash or blink screen of style transition.
That simple HTML code without any CSS is applied default styles of
the web browser as below.
body {
display: block;
margin: 8px;
}
To see it, open the Developer Tools of Google Chrome, then select the
“Elements” tab; select the <body> element and switch to the “Styles”
panel.
CHAPTER 12
CSS Selectors
style.css
body * p {
color: red;
}
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p>Some text</p>
</div>
<p>Another text</p>
</body>
</html>
style.css
p{
color: red;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p id="my-text">Some text</p>
</div>
<p>Another text</p>
</body>
</html>
style.css
#my-text {
color: red;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p class="my-text">Some text</p>
<p class="my-text">Another text</p>
</div>
<p>Another text</p>
</body>
</html>
style.css
.my-text {
color: red;
}
Result: Only two paragraphs, children of the <div> element, are red
since they have the class “ my-text .”
2.5 Multiple-class Selector
In CSS, we can select elements by using several classes (2 or more) in
the “ class ” attribute of the elements. The syntax is:
.class-name-1.class-name-2...class-name-n {
declaration block
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p class="my-text main">Some text</p>
<p class="my-text">Another text</p>
</div>
<p>Another text</p>
</body>
</html>
style.css
.my-text.main {
color: red;
}
.my-text {
color: blue;
}
Result: Only “Some text” is red since it has both “ my-text ” and
“ main ” classes.
2.6 CSS Pseudo-class
Pseudo-class is a CSS selector based on a specific state or position of
HTML elements.
2.6.1.2 :visited
In CSS, we use “ :visited ” to select visited links. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<a>This is not a link</a>
<a href="https://neodtruman.com" target="_blank">My Website</a>
<a href="https://fonts.google.com" target="_blank">Google Fonts</a>
</body>
</html>
style.css
:link {
color: green;
}
:visited {
color: red;
}
2.6.2 Cursor Interaction
2.6.2.1 :focus
In CSS, we use “ :focus ” to select elements having the focus.
2.6.2.2 :hover
In CSS, we use “ :hover ” to select elements with a mouse in front of
them.
2.6.2.3 :active
In CSS, we use “ :active ” to select elements being clicked.
style.css
:focus {
color: red;
}
:hover {
color: green;
}
:active {
color: blue;
}
button:hover {
color: green;
}
button:active {
color: blue;
}
2.6.3 Status of Elements
2.6.3.1 :enabled
In CSS, we use “ :enabled ” to select enabled elements.
2.6.3.2 :disabled
In CSS, we use “ :disabled ” to select disabled elements. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Update user's information</p>
<p>Username: <input type="text" value="username" disabled /></p>
<p>Email: <input type="text" value="email@company.com" /></p>
</body>
</html>
style.css
:enabled {
background-color: cyan;
}
:disabled {
background-color: #ccc;
}
2.6.3.3 :checked
In CSS, we use “ :checked ” to select checked radio buttons or
checkboxes. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Select your options:</p>
<p>
Gender:
<label><input type="radio" name="gender" /> <span>Male</span></label>
<label><input type="radio" name="gender" /> <span>Female</span></label>
</p>
<p>
<label><input type="checkbox" /> <span>Accept the agreement</span></label>
</p>
</body>
</html>
style.css
input:checked + span {
color: red;
}
2.6.4 Form Validation
2.6.4.1 :invalid
We use “ :invalid ” to select form elements if their values are not legal
according to the element's settings. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form action="">
<p>This text input must be a three-letter code:</p>
<input type="text" name="code" pattern="[A-Za-z]{3}" title="Three letter code." value="a"
/>
</form>
</body>
</html>
style.css
input:invalid {
background-color: lightpink;
}
2.6.4.2 :required
We use “ :required ” to select form elements that are required. For
example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form action="">
<p>This text input is required:</p>
<input type="text" name="fname" required />
</form>
</body>
</html>
style.css
input:required {
background-color: lightgreen;
}
2.6.4.3 :out-of-range
We use “ :out-of-range ” to select form elements with a value outside a
specified range according to the min and max attributes. For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form action="">
<p>This number input must be in the range of 1 - 6:</p>
<input type="number" name="quantity" min="1" max="6" value="8" />
</form>
</body>
</html>
style.css
input:out-of-range {
background-color: lightblue;
}
2.6.5 Child Elements
2.6.5.1 :first-child
In CSS, we use “ :first-child ” to select elements if they are the first
child of their parents.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p>Line 1</p>
<p>Line 2</p>
</div>
<p>Line 3</p>
<p>Line 4</p>
</body>
</html>
style.css
p:first-child {
color: red;
}
Result: only “ <p>Line 1</p> ” was selected because it is the first child.
2.6.5.2 :last-child
In CSS, we use “ :last-child ” to select elements if they are the last child
of their parents.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p>Line 1</p>
<p>Line 2</p>
</div>
<p>Line 3</p>
<p>Line 4</p>
</body>
</html>
style.css
p:last-child {
color: red;
}
style.css
p:nth-child(2) {
color: red;
}
style.css
p:nth-child(odd) {
color: red;
}
style.css
p:nth-child(even) {
color: red;
}
2.6.5.4 :nth-last-child(N)
:nth-last-child(N) is the reverted case of :nth-child(N) since it will
examine the children from the bottom of the list.
2.6.5.5 :only-child
In CSS, we use “ :only-child ” to select elements if they are the only
child of their parent.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p>Line 1</p>
</div>
<p>Line 2</p>
<p>Line 3</p>
</body>
</html>
style.css
p:only-child {
color: red;
}
Result: only “ <p>Line 1</p> ” was selected because it is the only child.
2.6.6 Type of elements
2.6.6.1 :first-of-type
In CSS, we use “ :first-of-type ” to select the first child element of the
specified element type.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<div>Line 1</div>
<p>Line 2</p>
<p>Line 3</p>
</div>
<p>Line 4</p>
</body>
</html>
style.css
p:first-of-type {
color: red;
}
style.css
p:last-of-type {
color: red;
}
style.css
p:nth-of-type(2) {
color: red;
}
Result: only “ <p>Line 3</p> ” was selected because it is the 2nd <p>
child.
2.6.6.4 :nth-last-of-type(N)
In CSS, we use “ :nth-last-of-type(N) ” to select the Nth last child
element of the specified element type.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Line 1</p>
<div>
<p>Line 2</p>
<p>Line 3</p>
<div>Line 4</div>
</div>
</body>
</html>
style.css
p:nth-last-of-type(2) {
color: red;
}
Result: only “ <p>Line 2</p> ” was selected because it is the 2nd last
<p> child (counting from the bottom).
2.6.6.5 :only-of-type
In CSS, we use “ :only-of-type ” to select the only child element of the
specified element type.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<div>Line 1</div>
<p>Line 2</p>
<p>Line 3</p>
</div>
<p>Line 4</p>
</body>
</html>
style.css
p:only-of-type {
color: red;
}
Result: only “ <p>Line 4</p> ” was selected because it is the only child
of type <p> .
2.6.7 Others Pseudo-classes
2.6.7.1 :root
The “ :root ” pseudo-class selects the HTML document’s root element,
the <html> element.
2.6.7.2 :empty
The “ :empty ” pseudo-class selects the empty elements.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div></div>
<div></div>
<div>This is not empty!</div>
</body>
</html>
style.css
div:empty {
height: 20px;
border: 1px solid red;
}
2.6.7.3 :target
The “ :target ” pseudo-class selects the target element by its ID.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<a href="#target1">Select target 1</a>
<a href="#target2">Select target 2</a>
<p id="target1">Target 1</p>
<p id="target2">Target 2</p>
</body>
</html>
style.css
:target {
border: 1px solid red;
}
Result when the user clicks on the link “Select target 2”:
2.6.7.4 :not(selector)
The “ :not(selector) ” pseudo-class is used to invert the selector .
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Update user's information</p>
<p>Address: <input type="text" value="Your address" /></p>
<p>Email: <input type="text" value="email@company.com" /></p>
<input type="submit" value="Submit" />
</body>
</html>
style.css
input:not([type="submit"]) {
background-color: cyan;
}
Result:
2.6.8 Pseudo-class Chain
We can chain pseudo-classes like the below example.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<a class="nav-lnk" href="#">Articles</a>
<a class="nav-lnk" href="#">Links</a>
<a class="nav-lnk" href="#">About</a>
<a class="nav-lnk" href="#">Newsletter</a>
</div>
</body>
</html>
style.css
.nav-lnk:not(:first-child):not(:last-child) {
color: red;
}
Result: Only the “Links” and “About” links are red since they are not
the first or last child.
2.7 CSS Pseudo-element
2.7.1 ::first-letter
The “ ::first-letter ” pseudo-element selects the first letter of an element.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>My heading</h1>
<p>My paragraph</p>
</body>
</html>
style.css
p::first-letter {
font-size: 30px;
color: red;
}
Result:
2.7.2 ::first-line
The “ ::first-line ” pseudo-element selects the first line of an element.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>My paragraph has<br />two lines.</p>
</body>
</html>
style.css
p::first-line {
color: red;
}
style.css
.required::before {
content: "* ";
color: red;
}
Result:
2.7.4 ::after
The “ ::after ” pseudo-element generates and renders the content right
after the element.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>
<label class="required">Username: </label>
<input type="text" />
</p>
<p>
<label>Email: </label>
<input type="text" />
</p>
</body>
</html>
style.css
.required::after {
content: "* ";
color: red;
}
Result:
2.7.5 ::selection
The “ ::selection ” pseudo-element defines the style for the selected text.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Please select some text in this paragraph.</p>
</body>
</html>
style.css
p::selection {
color: red;
background-color: yellow;
}
2.8 CSS Combined Selector
2.8.1 Descendant selector
We can select all elements that are descendants of a specified element.
The syntax is:
XY{
declaration blocks
}
The below example will select all <p> children of elements having the
class“ container .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div>
<p>Line 1</p>
</div>
<p>Line 2</p>
</div>
</body>
</html>
style.css
.container p {
color: red;
}
Result: <p>Line 1</p> and <p>Line 2</p> are red since they are
descendants of the <div class="container"> element.
2.8.2 Child Selector
We can select elements that are the immediate children of a specified
element. The syntax is:
X>Y{
declaration blocks
}
The below example will select all <p> elements that are immediate
children of elements having class “ container .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div>
<p>Line 1</p>
</div>
<p>Line 2</p>
</div>
</body>
</html>
style.css
.container > p {
color: red;
}
The below example will select all <p> elements that follow a <div>
element ( <p> and <div> are siblings).
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div>
<p>Line 1</p>
</div>
<p>Line 2</p>
<p>Line 3</p>
</div>
</body>
</html>
style.css
div + p {
color: red;
}
The example below will select all <p> siblings of a <div> element.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div>
<p>Line 1</p>
</div>
<p>Line 2</p>
<p>Line 3</p>
</div>
</body>
</html>
style.css
div ~ p {
color: red;
}
Result: <p>Line 2</p> and <p>Line 3</p> are red since they are
siblings of a <div> element.
2.9 CSS Attribute Selector
2.9.1 [attribute]
We can select elements that have a specific attribute by using this
syntax:
[attribute]
The example below will select <p> elements with the attribute
“ class .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p class="my-text">Some text</p>
</div>
<p>Another text</p>
</body>
</html>
style.css
[class] {
color: red;
}
The below example will select <p> elements having the attribute
“ class ” with the value “ my-text .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>
<p class="my-text">Some text</p>
</div>
<p class="another-text">Another text</p>
</body>
</html>
style.css
[class="my-text"] {
color: red;
}
The below example will select elements that have the “ class ” attribute
that begins with “ word ” (can be followed by a hyphen).
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>[class|="word"] { color: red; }</p>
<p class="word">Word class: "word"</p>
<p class="highlight word">Word class: "highlight word"</p>
<p class="word highlight">Word class: "word highlight"</p>
<p class="highlight-word">Word class: "highlight-word"</p>
<p class="word-highlight">Word class: "word-highlight"</p>
<p class="words">Word class: "words"</p>
</body>
</html>
style.css
[class|="word"] {
color: red;
}
The example below will select elements with the “ class ” attribute
containing “ word .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>[class~="word"] { color: red; }</p>
<p class="word">Word class: "word"</p>
<p class="highlight word">Word class: "highlight word"</p>
<p class="word highlight">Word class: "word highlight"</p>
<p class="highlight-word">Word class: "highlight-word"</p>
<p class="word-highlight">Word class: "word-highlight"</p>
<p class="words">Word class: "words"</p>
</body>
</html>
style.css
[class~="word"] {
color: red;
}
The example below will select elements with the “ class ” attribute that
starts with “ word .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>[class^="word"] { color: red; }</p>
<p class="word">Word class: "word"</p>
<p class="highlight word">Word class: "highlight word"</p>
<p class="word highlight">Word class: "word highlight"</p>
<p class="highlight-word">Word class: "highlight-word"</p>
<p class="word-highlight">Word class: "word-highlight"</p>
<p class="words">Word class: "words"</p>
</body>
</html>
style.css
[class^="word"] {
color: red;
}
The example below will select elements with the “ class ” attribute that
ends with “ word .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>[class$="word"] { color: red; }</p>
<p class="word">Word class: "word"</p>
<p class="highlight word">Word class: "highlight word"</p>
<p class="word highlight">Word class: "word highlight"</p>
<p class="highlight-word">Word class: "highlight-word"</p>
<p class="word-highlight">Word class: "word-highlight"</p>
<p class="words">Word class: "words"</p>
</body>
</html>
style.css
[class$="word"] {
color: red;
}
The example below will select elements with the “ class ” attribute
containing “ word .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p class="word">Word class: "word"</p>
<p class="highlight word">Word class: "highlight word"</p>
<p class="word highlight">Word class: "word highlight"</p>
<p class="highlight-word">Word class: "highlight-word"</p>
<p class="word-highlight">Word class: "word-highlight"</p>
<p class="words">Word class: "words"</p>
</body>
</html>
style.css
[class*="word"] {
color: red;
}
p{
color: red;
}
into this
div,
p{
color: red;
}
CHAPTER 13
CSS Cascading
When many duplicated CSS declarations apply to the same element, the
web browser will pick up only one style and apply it to the page using the
below cascading rules (the lower, the stronger).
style.css
h1 {
color: yellow;
}
h1 {
color: red;
}
Since we put the <link> element before the <style> element, all style
declarations are in this order:
h1 { color: yellow; }
h1 { color: red; }
h1 { color: green; }
h1 { color: blue; }
Therefore, we will see “My first heading” in blue as the last declaration
is “ h1 { color: blue; } .”
If the external CSS (style.css) is put after the tag <style> , the style
declarations are in this order:
h1 { color: green; }
h1 { color: blue; }
h1 { color: yellow; }
h1 { color: red; }
Example 1:
style.css
/* Type Selector */
h1 {
color: orange;
}
/* Universal Selector */
*{
color: red;
}
All headings are orange because “Type Selector” is more specific than
“Universal Selector” despite the order.
Example 2:
style.css
/* Combined Selector of Tags */
body h1 {
color: yellow;
}
/* Type Selector */
h1 {
color: orange;
}
All headings are green because “Class Selector” is more specific than
“Combined Selector of Tags” despite the order.
Example 4:
style.css
/* Combined Selector of Classes and Tags */
body .heading {
color: blue;
}
/* Class Selector */
.heading {
color: green;
}
All headings are blue because “Combined Selector of Classes and Tags”
is more specific than “Class Selector” despite the order.
Example 5:
style.css
/* Multiple-Class Selector */
.heading.first {
color: indigo;
}
/* Multiple-Class Selector */
.heading.first {
color: indigo;
}
The first heading is violet because “ID Selector” is more specific than
“Multiple-Class Selector” despite the order.
All-in-one example:
/* ID Selector */
#heading-one {
color: violet;
}
/* Multiple-Class Selector */
.heading.first {
color: indigo;
}
/* Class Selector */
.heading {
color: green;
}
/* Type Selector */
h1 {
color: orange;
}
/* Universal Selector */
*{
color: red;
}
Then open “Chrome DevTools > Elements > Styles” to check the
result (as in the below screenshot) after selecting the first heading in the
Elements panel.
The CSS declaration at the bottom of the CSS file will override the top.
However, the “Universal Selector” at line 32 has the lowest priority, so the
others override it.
3.3 Rule 3: Inline Style Is Preferred to both
Internal and External Styles
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<style>
#heading-one {
color: green;
}
</style>
</head>
<body>
<h1 id="heading-one" style="color: red">My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
style.css
.parent {
color: red;
}
.line {
color: green;
}
.first-line {
color: inherit;
}
CHAPTER 14
CSS Box Model
style.css
#my-element {
width: 200px;
height: 200px;
padding: 10px;
border: 5px solid red;
margin: 8px;
box-sizing: border-box;
}
4.1.2 Content Box
With “ content-box ” CSS, the padding and border are not included in
the total width and height of the element. Therefore, the actual size of the
element must be added padding and border.
index.html: use the same code as in the “Border Box” section.
style.css
#my-element {
width: 200px;
height: 200px;
padding: 10px;
border: 5px solid red;
margin: 8px;
box-sizing: content-box;
}
We have four CSS properties for the top, right, bottom, and left sides.
● margin-top
● margin-right
● margin-bottom
● margin-left
style.css
#parent {
border: 1px solid black;
}
#child {
border: 1px solid red;
margin-top: 50px;
margin-right: 30px;
margin-bottom: 50px;
margin-left: 30px;
}
Result:
4.2.1 Auto Margin
We can horizontally align an element using “ margin: auto; ” as in the
below example.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="parent">
<div id="child">This element has an auto margin.</div>
</div>
</body>
</html>
style.css
#parent {
border: 1px solid black;
height: 100px;
}
#child {
border: 1px solid red;
width: 200px;
margin: auto;
}
Result:
4.2.2 Collapsing Margins
The margin-bottom and margin-top could be collapsed, as in this
example.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="parent">
<div id="child-one">This element has a margin of 30px.</div>
<div id="child-two">This element has a margin of 60px.</div>
</div>
</body>
</html>
style.css
#parent {
border: 1px solid black;
}
#child-one {
border: 1px solid red;
margin: 30px;
}
#child-two {
border: 1px solid blue;
margin: 60px;
}
The #child-one element has a bottom margin of 30px , and the #child-
two element has a top margin of 60px , so the space (collapsing margin)
between them will be 60px (the more significant number).
4.3 CSS Outline
The outline is usually drawn outside the border but doesn’t take up
space like borders. These are outline properties:
outline-color, outline-style, outline-width
Example:
p{
outline-width: 5px;
outline-style: dotted;
outline-color: red;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
style.css
p{
outline: 5px dotted red;
border: 1px solid black;
}
The outline is drawn outside the border, as shown in this screenshot:
4.4 CSS Borders
The border of an HTML element is the space between its padding and
its margins, as in the below picture.
Example 2:
p{
border-top: 5px solid red;
border-right: 5px solid red;
border-bottom: 5px solid red;
border-left: 5px solid red;
}
or
p{
border-color: red;
border-style: solid;
border-width: 5px;
}
will have a shorthand like this
p{
border: 5px solid red;
}
Example 3:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
style.css
p{
border: 16px groove red;
}
4.4.2 CSS Border Radius
The “ border-radius ” property defines the radius of the HTML element's
corners. The property value can be an absolute length or a relative length.
There are four properties for the corners:
border-top-left-radius
border-top-right-radius
border-bottom-right-radius
border-bottom-left-radius
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>border-radius: 10px:</p>
<p id="p1"></p>
<p>border-radius: 50%:</p>
<p id="p2"></p>
</body>
</html>
style.css
p[id] {
padding: 20px;
width: 100px;
height: 50px;
background: green;
}
#p1 {
border-radius: 10px;
}
#p2 {
border-radius: 50%;
}
Result:
4.4.3 CSS Border Images
The “ border-image ” property allows you to specify an image to be
used as a border.
The property has three parts:
● the image to use as the border
● the position to slice the image
The border-image property takes a PNG image and slices it into nine
sections. It then places corners of the image at corners of the element, and
the middle sections of the image are repeated or stretched as you specify.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p id="border-img-round"></p>
<p id="border-img-stretch"></p>
</body>
</html>
style.css
#border-img-round {
border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 round;
}
#border-img-stretch {
border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 stretch;
}
Result:
4.5 CSS Padding
Padding is the area between the element’s content and its border.
Example 1:
p{
padding-top: 20px;
padding-right: 20px;
padding-bottom: 20px;
padding-left: 20px;
}
Example 2:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
style.css
p{
border: 1px solid black;
padding: 20px;
}
Result:
4.6 CSS Width and Height
We use “ width ” and “ height ” properties to set the content size of the
elements. However, we must consider the box-sizing property to calculate
the element's size.
We will use this HTML file in the next three examples:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
Example 1:
style.css
p{
border: 1px solid black;
width: 100px;
height: 100px;
}
Result:
Result:
Result:
CHAPTER 15
CSS Colors
We will use this HTML file in all the examples in this chapter:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
or
#rgb or #rgba
where:
● r: red
● g: green
● b: blue
● a: alpha. This value sets how transparent the color is.
Example:
style.css
p{
color: #ff0000;
background-color: #ff0;
}
5.3 RGB Colors
HTML elements can be set in color by using the RGB formula. The
syntax is:
rgb(red, green, blue)
or
rgba(red, green, blue, alpha)
The red, green, and blue parameters are integers from 0 to 255 .
The alpha parameter is a float number between 0 (fully transparent) and
1 (not transparent).
Example:
style.css
p{
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
}
or
rgb(0,0,0), rgb(17,17,17), rgb(34,34,34), ..., rgb(238,238,238), rgb(255,255,255)
CHAPTER 16
CSS Text
style.css
p{
text-decoration-line: underline;
}
.p1 {
text-decoration-style: double;
}
.p2 {
text-decoration-style: dotted;
}
.p3 {
text-decoration-style: dashed;
}
.p4 {
text-decoration-style: wavy;
}
Result:
The “ text-decoration ” property is a shorthand property for the four
properties above.
Example:
style.css
p{
text-decoration: underline red wavy 3px;
}
style.css
p{
white-space: pre-wrap;
}
style.css
.test-clip {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: clip;
}
.test-ellipsis {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: ellipsis;
}
Result:
6.1.6 Word Wrap
The “ word-wrap ” property allows long words to be broken and
wrapped onto the next line by setting its value to “ break-word .”
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p class="test-word-wrap">
This paragraph contains a very long word:
thisisaveryveryveryveryveryverylongword. The long word will break and wrap to the next
line.
</p>
</body>
</html>
style.css
.test-word-wrap {
width: 200px;
border: 1px solid #000000;
word-wrap: break-word;
}
Result:
6.1.7 Word Break
The “ word-break ” property specifies line-breaking rules. This property
can have one of these values:
● keep-all : this will break the whole word into a new line or break at
a hyphen
● break-word : this will break long words at arbitrary points into a
new line or break at a hyphen to prevent overflow
● break-all : the lines will break at any character
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>Testing "word-break: keep-all"</p>
<p class="test-keep-all">This is a-very-long-hyphen word, and this is
averyveryveryveryveryverylong word.</p>
style.css
p[class] {
width: 140px;
border: 1px solid #000000;
}
.test-keep-all {
word-break: keep-all;
}
.test-break-word {
word-break: break-word;
}
.test-break-all {
word-break: break-all;
}
Result:
6.2 Text Spacing
We will use this HTML file in all the examples in this section:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This paragraph is for testing.</p>
<p class="test-one">This paragraph is for testing.</p>
<p class="test-two">This paragraph is for testing.</p>
</body>
</html>
.test-two {
letter-spacing: 1px;
}
Result:
6.2.2 Word Spacing
The “ word-spacing ” property is used to specify the space between the
words in a text.
style.css
.test-one {
word-spacing: -5px;
}
.test-two {
word-spacing: 5px;
}
Result:
6.2.3 Line Height
The “ line-height ” property is used to specify the space between lines.
Its value can be:
● a number that will be multiplied by the current font-size to set the
line height
● %: a line height in percent of the current font size
● a fixed line height (in px, pt, cm , etc.).
style.css
p{
border: 1px solid black;
font-size: 20px;
}
.test-one {
line-height: 80%; /* 20px * 80% = 16px */
}
.test-two {
line-height: 2.3; /* 20px * 2.3 = 46px */
}
Result:
style.css
div {
height: 100px;
border: 1px solid black;
}
span {
line-height: 100px;
}
Result:
6.3 Text Position
6.3.1 Text Align
The “text-align” property is used to set the horizontal alignment of a
text. Its value can be left, right, center , or justify .
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This paragraph is for testing. This paragraph is for testing. This paragraph is for testing.
</p>
<p class="test-one">This paragraph is for testing. This paragraph is for testing. This paragraph
is for testing.</p>
<p class="test-two">This paragraph is for testing. This paragraph is for testing. This paragraph
is for testing.</p>
<p class="test-three">This paragraph is for testing. This paragraph is for testing. This
paragraph is for testing.</p>
</body>
</html>
style.css
p{
width: 150px;
border: 1px solid black;
}
.test-one {
text-align: justify;
}
.test-two {
text-align: center;
}
.test-three {
text-align: right;
}
Result:
6.3.2 Text Indent
The “ text-indent ” property is used to specify the indentation of the first
line of a text.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>
This paragraph is for testing. This paragraph is for testing. This paragraph is for testing.
</p>
<p class="test">
This paragraph is for testing. This paragraph is for testing. This paragraph is for testing.
</p>
</body>
</html>
style.css
p{
width: 150px;
border: 1px solid black;
}
.test {
text-indent: 30px;
}
Result:
6.4 CSS Fonts
We will use this HTML file in all the examples in this section:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This Paragraph Is for Testing.</p>
</body>
</html>
We can check the rendered font of an element using the Developer Tools
of the browser. First, go to the “Elements” tab, and select the <p>
element. Then, select the “Computed” panel (beside the “Styles” panel).
We can see at the bottom of the screenshot that the rendered font is “ Segoe
UI .”
I used Chrome to test the example. Since my Chrome does not have the
font “ Helvetica Neue ,” it uses “ Segoe UI ” to render the text.
6.4.2 Font Size
The “ font-size ” property sets the size of the text.
style.css
html {
/* font-size: 10px; */
font-size: 62.5%;
}
p{
font-size: 2.5rem;
}
p{
font-family: "Dyna Puff";
}
Result:
CHAPTER 17
CSS Backgrounds
Result:
7.1.2 background-image
The “ background-image ” property uses one or more images to render
the background of elements.
Example 1:
style.css
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("bg.jpg");
}
It can be seen that the last images at the right and bottom edges have
been clipped as they do not fit into the element.
We can add multiple images to an element’s background like this.
Example 2:
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("another-bg.png"), url("bg.jpg");
}
7.1.3 background-repeat
The “ background-repeat ” property specifies how the background
image is repeated. This property can have one of these values:
● repeat (default value) - The background image is repeated vertically
and horizontally.
● repeat-x - The background image is repeated only horizontally.
Result:
Example 2:
style.css
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("bg.jpg");
background-repeat: repeat-y;
}
Result:
Example 3:
style.css
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("bg.jpg");
background-repeat: space;
}
Result:
Example 4:
style.css
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("bg.jpg");
background-repeat: round;
}
Example 5: we can set the property to “ no-repeat ” to stop the
repeating.
p{
color: red;
border: 1px solid red;
width: 380px;
height: 380px;
background-image: url("bg.jpg");
background-repeat: no-repeat;
}
7.1.4 background-position
The “ background-position ” property specifies the starting position of
the background image. This property can have one of these values:
● x y - where the top left corner is “0 0.”
● x% y% - The top left corner is “0% 0%” and the right bottom
corner is “100% 100%.”
● or one of these: left top, left center, left bottom, right top, right
center, right bottom, center top, center center, center bottom .
style.css
p{
color: red;
border: 1px solid red;
width: 300px;
height: 180px;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-position: right top;
}
Result:
7.1.5 background-size
The “ background-size ” property allows you to change the size of the
background image.
● w h - width and height of the background image
Result:
Example 2:
style.css
p{
color: red;
border: 1px solid red;
width: 300px;
height: 180px;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-size: 50% 66%;
}
Result:
Example 3:
style.css
p{
color: red;
border: 1px solid red;
width: 200px;
height: 100px;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-size: contain;
}
7.1.7 background-clip
The “ background-clip ” property specifies the drawing area of the
background (image or color). The property can have one of these values:
● border-box - (default) the background is painted to the outside edge
of the border
● padding-box - the background is painted to the outside edge of the
padding
● content-box - the background is painted within the content box
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>No background-clip (border-box is default):</p>
<p class="bg">This is a paragraph.</p>
<p>background-clip: padding-box:</p>
<p class="bg padding">This is a paragraph.</p>
<p>background-clip: content-box:</p>
<p class="bg content">This is a paragraph.</p>
</body>
</html>
style.css
.bg {
border: 10px dotted black;
padding: 20px;
background: yellow;
}
.padding {
background-clip: padding-box;
}
.content {
background-clip: content-box;
}
Result:
7.1.8 background-origin
The “ background-origin ” property specifies where the background
image is positioned. The property can have one of these values:
● border-box - the background image starts from the border
<p>background-origin: border-box:</p>
<p class="bg border-box">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>background-origin: content-box:</p>
<p class="bg content-box">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam
nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</body>
</html>
style.css
.bg {
width: 300px;
height: 100px;
color: red;
border: 10px solid red;
padding: 35px;
background: url(bg.jpg);
background-repeat: no-repeat;
}
.border-box {
background-origin: border-box;
}
.content-box {
background-origin: content-box;
}
Result:
7.1.9 background-attachment
The “ background-attachment ” property specifies if the background
image scrolls with the rest of the page or not. This property can have one of
these values:
● scroll (default value) - The background image will scroll with the
page.
● fixed - The background image will not scroll with the page.
● local - The background image will scroll with the element's
contents.
Example 1:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>This is a header with height of 60px.</header>
<div class="fixed"></div>
<footer></footer>
</body>
</html>
style.css
body {
margin: 0;
}
header {
height: 60px;
}
.fixed {
background-position: center 60px;
height: 500px;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-attachment: fixed;
}
footer {
height: 1000px;
background-color: lightgreen;
}
style.css
p{
width: 120px;
height: 200px;
overflow: auto;
border: 1px solid black;
background-image: url("bg.jpg");
background-repeat: no-repeat;
background-attachment: local;
}
7.2 CSS Gradient Backgrounds
A color gradient consists of two or more colors that blend, transitioning
from one color to another over a given distance.
We will use this HTML file in all the examples in this section:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
Result:
Linear gradient “left to right”:
Example 2:
style.css
p{
height: 100px;
background: linear-gradient(to right, red, yellow);
}
Result:
Result:
Example 4:
style.css
p{
height: 100px;
background: linear-gradient(-90deg, red, yellow);
}
Result:
Result:
Example 1: Radial gradient with evenly spaced color stops (this is the
default).
style.css
p{
height: 100px;
background: radial-gradient(red, yellow, green);
}
Result:
Result:
Result:
Example 1:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="sprite testing"></div>
<div class="sprite number-1"></div>
<div class="sprite number-2"></div>
<div class="sprite number-3"></div>
<div class="sprite number-4"></div>
<div class="sprite number-5"></div>
<div class="sprite number-6"></div>
<div class="sprite number-7"></div>
<div class="sprite number-8"></div>
<div class="sprite number-9"></div>
</body>
</html>
style.css
.sprite {
background-image: url("sprites.jpg");
height: 50px;
width: 50px;
margin: 5px;
display: inline-block;
}
.testing {
background-position: -10px -10px;
}
.number-1 {
background-position: 0 0;
}
.number-2 {
background-position: -50px 0;
}
.number-3 {
background-position: -100px 0;
}
.number-4 {
background-position: 0 -50px;
}
.number-5 {
background-position: -50px -50px;
}
.number-6 {
background-position: -100px -50px;
}
.number-7 {
background-position: 0 -100px;
}
.number-8 {
background-position: -50px -100px;
}
.number-9 {
background-position: -100px -100px;
}
Result:
It can be seen that CSS sprites use the background-position property to
shift a portion of a big image into a smaller viewport like the <div
class="sprite testing"> element.
We often use the image sprite in the navigation bar like this.
Example 2:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<ul class="navlist">
<li class="sprite home"><a href="#home"></a></li>
<li class="sprite prev"><a href="#prev"></a></li>
<li class="sprite next"><a href="#next"></a></li>
</ul>
</body>
</html>
style.css
.navlist li {
margin: 0;
padding: 0;
list-style: none;
float: left;
}
.navlist li,
.navlist a {
display: block;
height: 50px;
width: 50px;
}
.sprite {
background-image: url("sprites.jpg");
}
.home {
background-position: 0 0;
}
.home:hover {
background-position: 0 -50px;
}
.prev {
background-position: -50px 0;
}
.prev:hover {
background-position: -50px -50px;
}
.next {
background-position: -100px 0;
}
.next:hover {
background-position: -100px -50px;
}
CHAPTER 18
CSS Display
style.css
.container {
border: 1px solid black;
width: 300px;
height: 100px;
}
.inline-blocks {
display: inline-block;
border: 1px solid red;
height: 40px;
}
.normal-blocks {
border: 1px solid blue;
}
Result:
This example is another way to make elements float without the “ float ”
property.
8.1.2 visibility
To hide the element but still take up the same space of it as before, we
use the “ visibility ” property.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p>This is the <span class="hidden">hidden</span> element</p>
<p>This is the <span class="invisible">invisible</span> element</p>
</body>
</html>
style.css
.hidden {
display: none;
}
.invisible {
visibility: hidden;
}
Result:
8.2 CSS object-fit
The CSS “ object-fit ” property is used to specify how the object (image
or video) should be resized to fit its container (the <img> or <video>
elements). The property can have the following values:
● fill (default value) - The object is resized to fill the element's
content box. If necessary, the object will be distorted to fit.
● contain - The object is scaled to maintain its aspect ratio while
fitting within the element's content box.
● cover - The object is scaled to maintain its aspect ratio while filling
the element's entire content box. The object will be clipped to fit.
● none - The object is not resized.
Example 1:
style.css
img {
width: 300px;
height: 200px;
border: 1px solid red;
object-fit: contain;
}
Result:
Example 2:
style.css
img {
width: 300px;
height: 200px;
border: 1px solid red;
object-fit: cover;
}
Result:
Example 3:
style.css
img {
width: 300px;
height: 200px;
border: 1px solid red;
object-fit: none;
}
Result:
Example 4:
style.css
img {
width: 150px;
height: 100px;
border: 1px solid red;
object-fit: scale-down;
}
Result:
8.3 Cursor
The “ cursor ” property specifies how the mouse’s pointer looks when
the user hovers it on an element. These are popular values of this property:
● pointer - The cursor is a pointer
● not-allowed - The cursor indicates that the requested action will not
be executed
● grab - The cursor indicates that something can be grabbed
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<p class="my-element">This is a paragraph</p>
</body>
</html>
style.css
.my-element {
cursor: pointer;
}
8.4 CSS Overflow
The overflow property specifies how the overflowed content is
rendered inside its containing element.
This file will be used in the following examples:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="child">I am the content.</div>
</div>
</body>
</html>
8.4.1 overflow: visible
By default, the overflow is visible. It means that the content will be
rendered outside its parent.
Example:
style.css
.container {
border: 1px solid black;
width: 200px;
height: 100px;
}
.child {
margin: 10px;
border: 1px solid red;
background-color: white;
height: 150px;
}
Result:
8.4.2 overflow: hidden
With the “ hidden ” value, the overflowed content will be hidden.
Example:
style.css
.container {
overflow: hidden;
border: 1px solid black;
width: 200px;
height: 100px;
}
.child {
margin: 10px;
border: 1px solid red;
background-color: white;
height: 150px;
}
Result:
8.4.3 overflow: scroll
Setting the value to “ scroll ,” horizontally and vertically scrollbars are
added to view the overflowed content. The two scrollbars are always shown
despite needing.
Example:
style.css
.container {
overflow: scroll;
border: 1px solid black;
width: 200px;
height: 100px;
}
.child {
margin: 10px;
border: 1px solid red;
background-color: white;
height: 150px;
}
Result:
8.4.4 overflow: auto
The “ auto ” value will add scrollbars when necessary.
Example:
style.css
.container {
overflow: auto;
border: 1px solid black;
width: 200px;
height: 100px;
}
.child {
margin: 10px;
border: 1px solid red;
background-color: white;
height: 150px;
}
Result:
8.5 CSS Opacity
The “ opacity ” property sets the transparency of an element and all its
children, including backgrounds and texts. Its valid value is a float from 0.0
to 1.0, where 0 is completely transparent and 1 is not transparent.
The example below also compares the “ opacity ” property and the
transparent“ background-color .” Again, we use the transparent background
color to keep the text unchanged.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="child">I'm a child element</div>
</div>
<div class="container opacity">
<div class="child">I'm a child element</div>
</div>
<div class="container transparent">
<div class="child">I'm a child element</div>
</div>
</body>
</html>
style.css
.container {
background-color: rgb(255, 0, 0);
padding: 20px;
margin: 10px;
}
.container.opacity {
opacity: 0.5;
}
.container.transparent {
background-color: rgba(255, 0, 0, 0.5);
}
.child {
border: 1px solid black;
}
Result:
8.6 CSS Shadows
We can add shadows to text and HTML elements using CSS.
8.6.1 text-shadow
The “ text-shadow ” property adds a shadow to text and accepts a
comma-separated list of shadows. The syntax is:
text-shadow: h-offset v-offset blur-radius color
where:
● h-offset - The horizontal position of the shadow (allows negative
values to put the shadow on the left side of the text).
● v-offset - The vertical position of the shadow (allows negative
values to put the shadow above the text).
● blur-radius (optional) - The higher the number, the more blurred the
shadow will be.
● color (optional) - The color of the shadow (The default value is the
text color).
Example 1:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>
style.css
h1 {
text-shadow: 3px 3px red;
}
Result:
Result:
Result:
Example 4:
The below CSS creates a 2px border around the text. The solution is
straightforward, so we create four shadows (without blur) and then shift
them left (-2px 0 black), bottom (0 2px black), right (2px 0 black), and top
(0 -2px black), each side 2px.
h1 {
color: white;
text-shadow: -2px 0 black, 0 2px black, 2px 0 black, 0 -2px black;
}
Result:
8.6.2 box-shadow
The “ box-shadow ” property adds one or more shadows to an element.
The syntax is:
box-shadow: h-offset v-offset blur-radius spread color
where:
● h-offset - The horizontal position of the shadow (allows negative
values to put the shadow on the left side of the text).
● v-offset - The vertical position of the shadow (allows negative
values to put the shadow above the text).
● blur-radius (optional) - The higher the number, the more blurred the
shadow will be.
● spread (optional) - A positive value increases the size of the
shadow; a negative value decreases the size of the shadow.
● color (optional) - The color of the shadow (The default value is the
text color).
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>This is a div</div>
</body>
</html>
style.css
Example 1:
div {
border: 1px solid black;
box-shadow: 5px 5px grey;
}
Result:
Example 2: To make it real, we should put a blur number into the CSS
at the 3rd position.
div {
border: 1px solid black;
box-shadow: 5px 5px 5px grey;
}
Result:
Result:
Example 4: To add more than one shadow to the text, you can add a
comma-separated list of shadows.
div {
border: 1px solid black;
box-shadow: 8px 0 10px grey, 0 8px 10px grey;
}
Result:
8.7 CSS Multiple Columns
The CSS multi-column layout allows easy definition of multiple
columns of text - like the newspapers.
style.css
.newspaper {
column-count: 3;
column-gap: 40px;
column-rule-style: solid;
column-rule-width: 1px;
column-rule-color: black;
}
Result:
Try to resize the browser to see how the number of columns will change
based on the viewport’s width.
style.css
.newspaper {
column-count: 3;
column-gap: 40px;
column-rule: 1px solid black;
}
h1 {
column-span: all;
}
Result:
8.8 CSS Tables
Below is a simple table.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Corner</td>
</tr>
<tr>
<td>Neo</td>
<td>D. Truman</td>
</tr>
</tbody>
</table>
</body>
</html>
Example 1:
style.css
table {
border: 1px solid green;
}
th {
border: 1px solid red;
}
td {
border: 1px solid blue;
}
Result:
We see double borders because of the space between cells inside the
table.
The “ border-collapse ” property sets whether the table borders should
be collapsed into a single border.
Example 2:
style.css
table {
border-collapse: collapse;
border: 1px solid green;
}
th {
border: 1px solid red;
}
td {
border: 1px solid blue;
}
Result:
8.8.1 Table Sizing
We can set the table’s width and height or its cells’ width and height
using “ width ” and “ height ” properties. For example:
style.css
table {
border-collapse: collapse;
border: 1px solid green;
width: 100%;
}
th {
border: 1px solid red;
height: 30px;
}
td {
border: 1px solid blue;
height: 50px;
}
Result:
8.8.2 Text Alignment in Table Cells
We can align text inside cells using “ text-align ” (with value: left, right,
center, justify ) and “ vertical-align ” (with value: baseline, length, sub,
super, top, text-top, middle, bottom, text-bottom ) properties. For example:
style.css
table {
border-collapse: collapse;
border: 1px solid green;
width: 100%;
}
th {
border: 1px solid red;
height: 30px;
}
td {
border: 1px solid blue;
height: 50px;
text-align: center;
vertical-align: top;
}
Result:
8.9 CSS Lists
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.
style.css
.col {
display: inline-block;
width: 150px;
}
ul.circle {
list-style-type: circle;
}
ul.square {
list-style-type: square;
}
ol.upper-roman {
list-style-type: upper-roman;
}
ol.lower-alpha {
list-style-type: lower-alpha;
}
Result:
The “ list-style-image ” property specifies an image as the list item
marker.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
style.css
ul {
list-style-image: url("marker.png");
}
style.css
ul {
list-style-position: inside;
}
style.css
div {
width: 200px;
border: 1px solid black;
}
.test {
transform: translate(30px, 60px);
}
Result:
.test {
position: relative;
left: 100px;
top: 30px;
transform: scale(2, 3);
}
Result:
8.10.3 Rotates an Element
We can rotate an HTML element by using one of these CSS
declarations:
● transform: rotateX(angle) - Defines a rotation along the X-axis.
style.css
.div2 {
transform: rotate(180deg);
}
.div3 {
transform: rotate(-20deg);
}
Result:
The rotateX(), rotateY() , or rotateZ() method rotates an element
around its X-axis, Y-axis, or Z-axis at a given degree.
Example 2:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>A paragraph</div>
<div class="test1">1st paragraph</div>
<div class="test2">2nd paragraph</div>
<div class="test3">3rd paragraph</div>
</body>
</html>
style.css
div {
border: 1px solid black;
}
.test1 {
transform: rotateX(150deg);
}
.test2 {
transform: rotateY(150deg);
}
.test3 {
transform: rotateZ(-100deg);
}
Result:
8.10.4 Skews an Element
We can skew an HTML element by using one of these CSS declarations:
● transform: skewX(angle) - Skews an element along the X-axis.
● transform: skewY(angle) - Skews an element along the Y-axis.
● transform: skew(x-angle,y-angle) - Defines a 2D skew
transformation along the X-axis and Y-axis.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>A paragraph</div>
<div class="test1">1st paragraph</div>
<div class="test2">2nd paragraph</div>
<div class="test3">3rd paragraph</div>
</body>
</html>
style.css
div {
border: 1px solid black;
}
.test1 {
transform: skewX(30deg);
}
.test2 {
transform: skewY(-10deg);
}
.test3 {
position: relative;
top: 60px;
transform: skew(20deg, 10deg);
}
Result:
CHAPTER 19
CSS Layout
The layout is the way HTML elements are placed on a web page. We often
use CSS to build a design by arranging the elements into our preferred
visual structure.
19.1.2 relative
An element with “ position: relative ” is relative to its normal position.
We use the top, right, bottom , and left properties to set the element’s
position.
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="parent">
<div class="normal">Normal element</div>
<div class="relative">I am relative!</div>
</div>
</body>
</html>
style.css
.parent {
width: 200px;
height: 200px;
border: 1px dashed black;
}
.relative {
position: relative;
left: 30px;
top: 30px;
border: 1px solid red;
}
.normal {
border: 1px dashed blue;
}
Result:
19.1.3 absolute
An element with “ position: absolute ” is positioned relative to the
nearest positioned ancestor.
style.css
.positioned {
position: relative;
border: 1px solid black;
width: 200px;
height: 200px;
}
.non-positioned {
border: 1px dashed black;
width: 150px;
height: 150px;
}
.absolute {
position: absolute;
right: 30px;
top: 30px;
border: 1px solid red;
background-color: white;
}
19.1.4 fixed
An element with “ position: fixed ” is positioned relative to the
viewport, which means it always stays in the same place even if the page is
scrolled.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div>Normal element</div>
<div class="fixed">I am fixed!</div>
<div class="big">A big element.</div>
</body>
</html>
style.css
.big {
height: 1000px;
border: 1px solid black;
}
.fixed {
position: fixed;
right: 30px;
top: 30px;
width: 100px;
border: 1px solid red;
}
19.1.5 sticky
An element with “ position: sticky ” is left in the normal flow until the
conditions that trigger its stickiness come to pass.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="parent">
<p>Try to scroll inside this frame to understand how sticky positioning works.</p>
<div class="sticky">I am sticky!</div>
<p>In this example, the sticky element sticks to the top of the page when it reaches the
position "top: 0".</p>
<p>Scroll back up to remove the stickiness.</p>
<p>Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum,
altera fabulas ut quo.</p>
</div>
</body>
</html>
style.css
.parent {
width: 200px;
height: 200px;
overflow: auto;
}
.sticky {
position: sticky;
top: 0;
border: 1px solid red;
background-color: white;
}
9.2 CSS Float
19.2.1 float
Make elements float inside their containing element. There are several
use cases:
● “ float: none ” (default value) - Elements are placed in the normal
flow.
● “ float: left ” - Elements float on the left side of their parent.
● “ float: right ” - Elements float on the right side of their parent but in
reverted order.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="child">I'm the 1st child</div>
<div class="child">I'm the 2nd child</div>
</div>
</body>
</html>
style.css
.container {
border: 1px solid black;
width: 300px;
height: 100px;
}
.child {
float: right;
border: 1px solid red;
}
Result:
19.2.2 clear
The example below shows us that the 3rd element is not placed in the
expected place.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="float">I'm the 1st child</div>
<div class="float">I'm the 2nd child</div>
<div class="no-float">I'm the 3rd child</div>
</div>
</body>
</html>
style.css
.container {
border: 1px solid black;
width: 300px;
height: 100px;
}
.float {
float: left;
border: 1px solid red;
}
.no-float {
border: 1px solid blue;
}
Result:
Result:
Two other options of the “ clear ” property are “ clear: right; ” or “ clear:
both; .”
9.3 CSS Z-index
The “ z-index ” property specifies the order of positioned elements on
the Z-axis.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="absolute child z-index-minus-two">z-index: -2</div>
<div class="absolute child z-index-minus-one">z-index: -1</div>
<div class="absolute child z-index-zero">z-index: 0</div>
<div class="absolute child z-index-one">z-index: 1</div>
<div class="child z-index-two">z-index: 2; but I'm not positioned</div>
</div>
</body>
</html>
style.css
div {
border: 1px solid black;
}
.container {
position: relative;
width: 250px;
height: 250px;
}
.child {
width: 100px;
height: 100px;
background-color: white;
}
.absolute {
position: absolute;
border: 1px solid red;
text-align: right;
}
.z-index-minus-two {
z-index: -2;
left: 100px;
top: 5px;
}
.z-index-minus-one {
z-index: -1;
left: 70px;
top: 35px;
}
.z-index-zero {
z-index: 0;
left: 40px;
top: 65px;
}
.z-index-one {
z-index: 1;
left: 10px;
top: 95px;
}
.z-index-two {
z-index: 2;
}
Result:
9.4 CSS Flexbox
A flexible box or flexbox ensures that elements behave predictably
when the page layout must accommodate different screen sizes and display
devices. A flex container is declared by setting the “ display ” property of an
element to either “ flex ” (rendered as a block) or “ inline-flex ” (rendered
as inline).
Inside a flex container, there are one or more flex items. Flex items are
positioned inside a flex container along a flex line. By default, there is only
one flex line per flex container.
The following example shows three flex items. They are positioned by
default: along the horizontal flex line from left to right.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="flex-container">
<div class="flex-item item1">flex item 1</div>
<div class="flex-item item2">flex item 2</div>
<div class="flex-item item3">flex item 3</div>
</div>
</body>
</html>
style.css
.flex-container {
display: flex;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
9.4.1 Flex Container
9.4.1.1 gap
The “ gap ” property is used to create space between flex items. As in
the previous example, the gap between flex items is 10 pixels.
9.4.1.2 flex-direction
The “ flex-direction ” property specifies the direction of the flexible
items inside the flex container. The default value of flex-direction is row
(left-to-right).
The other values are as follows:
● row - The flex items are displayed horizontally as a row.
● row-reverse - Same as row, but the flex items will be laid out right
to the left.
● column - The flex items are displayed vertically as a column.
● column-reverse - Same as the column, but in reverse order.
Example 1:
style.css
.flex-container {
display: flex;
flex-direction: row-reverse;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 2:
style.css
.flex-container {
display: flex;
flex-direction: column;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 3:
style.css
.flex-container {
display: flex;
flex-direction: column-reverse;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
9.4.1.3 justify-content
The “ justify-content ” property horizontally aligns the flexible
container's items when the items do not use all available space.
The possible values are as follows:
● flex-start (default value) - Items are positioned at the beginning of
the container.
● flex-end - Items are positioned at the end of the container.
.flex-item {
border: 1px solid red;
}
Result:
Example 2:
style.css
.flex-container {
display: flex;
justify-content: center;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 3:
style.css
.flex-container {
display: flex;
justify-content: space-between;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 4:
style.css
.flex-container {
display: flex;
justify-content: space-around;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 5:
style.css
.flex-container {
display: flex;
justify-content: space-evenly;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
9.4.1.4 align-items
The “ align-items ” property vertically aligns the flexible container's
items when the items do not use all available space.
The possible values are as follows:
● stretch (default value) - Items are stretched to fit the container
● flex-start - Items are positioned at the top of the container
● flex-end - Items are positioned at the bottom of the container
Example 1:
style.css
.flex-container {
display: flex;
align-items: flex-start;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 2:
style.css
.flex-container {
display: flex;
align-items: flex-end;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 3:
style.css
.flex-container {
display: flex;
align-items: center;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
Result:
Example 4:
style.css
.flex-container {
display: flex;
align-items: baseline;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.item1 {
height: 50px;
}
.item2 {
line-height: 80px;
}
Result:
9.4.1.5 flex-wrap
The “ flex-wrap ” property specifies whether the flex items should wrap
or not if there is not enough room for them on one flex line.
The possible values are as follows:
● nowrap (default value) - The flexible items will not wrap
● wrap - The flexible items will wrap if necessary
● wrap-reverse - The flexible items will wrap, if necessary, in reverse
order
Example 1:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 2:
style.css
.flex-container {
display: flex;
flex-wrap: wrap-reverse;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
9.4.1.6 align-content
The “ align-content ” property modifies the behavior of the “ flex-
wrap ” property as it aligns flex lines of wrapping items. The possible
values are as follows:
● stretch (default value) - Lines stretch to take up the remaining space
● flex-start - Lines are packed toward the start of the flex container
● flex-end - Lines are packed toward the end of the flex container
● center - Lines are packed toward the center of the flex container
● space-between - Lines are evenly distributed in the flex container
● space-around - Lines are evenly distributed in the flex container,
with half-size spaces on either end
● space-evenly - Items will have equal space around them.
Example 1:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: flex-start;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 2:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: flex-end;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 3:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: center;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 4:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: space-between;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 5:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: space-around;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
Example 6:
style.css
.flex-container {
display: flex;
flex-wrap: wrap;
align-content: space-evenly;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result:
9.4.2 Flex Items
9.4.2.1 flex-basis
The “ flex-basis ” property defines an item’s width if the original width
is smaller than the flex-basis value.
Example:
style.css
.flex-container {
display: flex;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 120px;
}
Result: The flex items were expanded as much as possible to reach the
flex-basis size.
9.4.2.2 order
The “ order ” property controls the order of items. The items with no
“ order ” value will be settled first; then come the smallest order value, and
the highest order value makes the item last.
style.css
.flex-container {
display: flex;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.item1 {
order: 2;
}
.item2 {
order: 1;
}
Result:
9.4.2.3 flex-grow
The “ flex-grow ” property allows an element to grow (0 means no).
Example:
style.css
.flex-container {
display: flex;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.item1 {
flex-grow: 1;
}
.item2 {
flex-grow: 2;
}
9.4.2.4 flex-shrink
The “ flex-shrink ” property allows an element to shrink (0 means no).
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="flex-container">
<div class="flex-item item1">Item 1</div>
<div class="flex-item item2">Item 2</div>
<div class="flex-item item3">Item 3</div>
<div class="flex-item item4">Item 4</div>
<div class="flex-item item5">Item 5</div>
</div>
</body>
</html>
style.css
.flex-container {
display: flex;
width: 400px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
flex-basis: 100px;
}
.item2 {
flex-shrink: 3;
}
Result: Since the container width is 400px, but there are five items with
flex-basis of 100px , all the items must be shrunk. The second item with
“ flex-shrink: 3 ” will be the smallest one since its shrinking space is three
times that of other items.
9.4.2.5 align-self
The “ align-self ” property of flex items overrides the “ align-items ”
property of its parent.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="flex-container">
<div class="flex-item item1">flex-start</div>
<div class="flex-item item2">flex-end</div>
<div class="flex-item item3">center</div>
<div class="flex-item item4">baseline</div>
<div class="flex-item item5">stretch</div>
</div>
</body>
</html>
style.css
.flex-container {
display: flex;
align-items: center;
width: 300px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.item1 {
align-self: flex-start;
}
.item2 {
align-self: flex-end;
}
.item4 {
align-self: baseline;
}
.item5 {
align-self: stretch;
}
Result:
9.4.2.6 flex
The “ flex ” property is the shorthand for flex-grow , flex-shrink , and
flex-basis .
flex: 0 1 auto;
In the following example, the first flex item will consume 2/4 of the free
space, and the other two will consume 1/4 of the free space.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="flex-container">
<div class="flex-item item1">flex item 1</div>
<div class="flex-item item2">flex item 2</div>
<div class="flex-item item3">flex item 3</div>
</div>
</body>
</html>
style.css
.flex-container {
display: flex;
width: 400px;
height: 150px;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.item1 {
flex: 2;
}
.item2 {
flex: 1;
}
.item3 {
flex: 1;
}
Result:
style.css
.flex-container {
display: flex;
width: 100%;
border: 1px solid black;
gap: 10px;
}
.flex-item {
border: 1px solid red;
}
.lnk-home {
margin-right: auto;
}
Result:
9.5 CSS Grid
While CSS flexbox works with a 1D array of items, CSS grid provides a
grid-based layout system with rows and columns. To define a grid
container, we set the “ display ” property to “ grid ” to create a block-level
grid or “ inline-grid ” to create an inline-level grid.
This file is used in the following examples:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="grid-container">
<div class="grid-item item1">Item 1</div>
<div class="grid-item item2">Item 2</div>
<div class="grid-item item3">Item 3</div>
<div class="grid-item item4">Item 4</div>
<div class="grid-item item5">Item 5</div>
<div class="grid-item item6">Item 6</div>
<div class="grid-item item7">Item 7</div>
<div class="grid-item item8">Item 8</div>
<div class="grid-item item9">Item 9</div>
</div>
</body>
</html>
9.5.1 Grid Container
9.5.1.1 grid-template-columns
The “ grid-template-columns ” property defines the number of columns
in the grid layout and the width of each column. The syntax is:
grid-template-columns: col-1-width col-2-width ... col-N-width
style.css
.grid-container {
display: grid;
grid-template-columns: auto auto auto;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.1.2 grid-template-rows
The “ grid-template-rows ” property defines the height of each row. The
syntax is:
grid-template-rows: row-1-height row-2-height ... row-N-height
.grid-item {
border: 1px solid red;
}
Result: The grid is horizontally divided into 6 fragments. Then, the first
column gets two fragments, the second column gets one fragment, and the
third column gets three fragments.
we can write:
grid-template-columns: repeat(3, 1fr);
9.5.1.3 column-gap
The “ column-gap ” property creates space between columns in the grid.
Example:
style.css
.grid-container {
display: grid;
grid-template-columns: 2fr 1fr 3fr;
grid-template-rows: 30px auto 60px;
column-gap: 10px;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.1.4 row-gap
The “ row-gap ” property creates space between rows in the grid.
Example:
style.css
.grid-container {
display: grid;
grid-template-columns: 2fr 1fr 3fr;
grid-template-rows: 30px auto 60px;
row-gap: 10px;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.1.5 gap
The “ gap ” property creates space between rows and columns in the
grid. It is a shorthand for the “ row-gap ” and “ column-gap ” properties.
The syntax is:
gap: row-gap column-gap
Example:
style.css
.grid-container {
display: grid;
grid-template-columns: 2fr 1fr 3fr;
grid-template-rows: 30px auto 60px;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.1.6 justify-items
The “ justify-items ” property horizontally aligns the grid container's
items when the items do not use all available space of the grid cells.
The possible values are as follows:
● stretch (default value) - Items are stretched to fit the cell
● start - Items are positioned on the left side of the cell
● end - Items are positioned on the right side of the cell
Example 1:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-items: start;
}
.grid-item {
border: 2px solid red;
}
Example 2:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-items: end;
}
.grid-item {
border: 2px solid red;
}
Example 3:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-items: center;
}
.grid-item {
border: 2px solid red;
}
● baseline - Items are aligned along the text baseline of the cell
Example 1:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-items: start;
}
.grid-item {
border: 2px solid red;
}
Example 2:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-items: end;
}
.grid-item {
border: 2px solid red;
}
Example 3:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-items: center;
}
.grid-item {
border: 2px solid red;
}
Result: (dotted lines are outlines of the grid cells)
9.5.1.8 justify-content
The “ justify-content ” property horizontally aligns the grid container's
items when the items do not use all available space.
The possible values are as follows:
● start - Items are positioned at the beginning of the container.
● end - Items are positioned at the end of the container.
● center - Items are positioned at the center of the container.
Example 1:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: start;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 2:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: end;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 3:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: center;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 4:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: space-between;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 5:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: space-around;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 6:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-content: space-evenly;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.1.9 align-content
The “ align-content ” property vertically aligns the rows inside the grid’s
container. The possible values are as follows:
● start - Rows are packed toward the top of the grid container
● end - Rows are packed toward the bottom of the grid container
● center - Rows are packed toward the center of the grid container
.grid-item {
border: 1px solid red;
}
Result:
Example 2:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-content: end;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 3:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-content: center;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 4:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-content: space-between;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 5:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-content: space-around;
}
.grid-item {
border: 1px solid red;
}
Result:
Example 6:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-content: space-evenly;
}
.grid-item {
border: 1px solid red;
}
Result:
9.5.2 Grid Items
We use grid lines to specify the location of a grid item. The grid lines
are assigned numbers along the X-axis and Y-axis. Horizontal lines are
called row-lines, and vertical lines are called column-lines.
9.5.2.1 grid-column-start
The “ grid-column-start ” property defines a grid item’s start location
within the grid by referring to the grid column-lines. The syntax is:
grid-column-start: start-column
● span <number> - the item will span the provided number of cells.
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
.item3 {
grid-column-start: 2;
}
Result:
9.5.2.2 grid-column-end
The “ grid-column-end ” property is similar to the “ grid-column-start ”
property, but it defines the ending location.
9.5.2.3 grid-column
The “ grid-column ” property is a shorthand for the “ grid-column-start ”
and “ grid-column-end ” properties. The syntax is:
grid-column: start-column / end-column
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
.item2 {
/* grid-column: 2 / 4; */
/* grid-column: 2 / -1; */
grid-column: 2 / span 2;
}
Result:
9.5.2.4 grid-row-start
The “ grid-row-start ” property defines a grid item’s start location within
the grid by referring to the grid row-lines. The syntax is:
grid-row-start: start-row
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
.item1 {
grid-row-start: 3;
}
Result:
9.5.2.5 grid-row-end
The “ grid-row-end ” property is similar to the “ grid-row-start ”
property, but it defines the ending location.
9.5.2.6 grid-row
The “ grid-row ” property is a shorthand for the “ grid-row-start ” and
“ grid-row-end ” properties. The syntax is:
grid-row: start-row / end-row
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
.item9 {
grid-column-start: 2;
/* grid-row: 1 / 3; */
grid-row: 1 / span 2;
}
Result:
9.5.2.7 grid-area
The “ grid-area ” property is a shorthand property for the “ grid-row-
start ,” “ grid-column-start ,” “ grid-row-end ,” and the “ grid-column-end ”
properties.
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
}
.grid-item {
border: 1px solid red;
}
.item6 {
grid-area: 1 / 3 / 5 / 4;
}
9.5.2.8 justify-self
The “ justify-self ” property overrides the “ justify-items ” property of
the grid container.
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
justify-items: start;
}
.grid-item {
border: 1px solid red;
}
.item5 {
justify-self: end;
}
Result:
9.5.2.9 align-self
The “ align-self ” property overrides the “ align-items ” property of the
grid container.
Example:
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
align-items: start;
}
.grid-item {
border: 1px solid red;
}
.item5 {
align-self: end;
}
Result:
9.5.2.10 grid-template-areas
The “ grid-template-areas ” property specifies areas within the grid
layout. We name the grid items using the “ grid-area ” property and then
refer to the name in the “ grid-template-areas ” property.
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="grid-container">
<div class="grid-item item1">Header</div>
<div class="grid-item item2">Menu</div>
<div class="grid-item item3">Main</div>
<div class="grid-item item4">Sidebar</div>
<div class="grid-item item5">Footer</div>
</div>
</body>
</html>
style.css
.grid-container {
display: grid;
width: 300px;
height: 150px;
border: 1px solid black;
grid-template-columns: auto auto auto;
gap: 10px;
grid-template-areas:
"header header header header header header"
"menu main main main sidebar sidebar"
"footer footer footer footer footer footer";
}
.grid-item {
border: 1px solid red;
}
.item1 {
grid-area: header;
}
.item2 {
grid-area: menu;
}
.item3 {
grid-area: main;
}
.item4 {
grid-area: sidebar;
}
.item5 {
grid-area: footer;
}
Result:
9.6 CSS Alignment
19.6.1 Horizontal Alignment
We use the CSS “ text-align ” property to align text. Please refer to the
section “CSS Text” for more details.
To align a block element center inside its containing element, we use the
CSS “ margin: auto; .”
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="child">I'm the child element</div>
</div>
</body>
</html>
style.css
.container {
border: 1px solid black;
width: 300px;
height: 60px;
}
.child {
border: 1px solid red;
width: 150px;
margin: auto;
}
Result:
Therefore, to center align an image, we could change it to a block
element and use “ margin: auto; ” like this.
img {
display: block;
margin: auto;
}
style.css
.container {
border: 1px solid black;
width: 300px;
}
.child {
border: 1px solid red;
margin-top: 50px;
margin-bottom: 50px;
}
Result:
style.css
.container {
position: relative;
border: 1px solid black;
width: 300px;
height: 150px;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid red;
}
.another-child {
border: 1px solid blue;
}
Result:
style.css
.flex-container {
display: flex;
width: 300px;
height: 160px;
border: 1px solid black;
}
.flex-item {
border: 1px solid red;
width: 80px;
height: 80px;
margin: auto;
}
Result:
CHAPTER 20
CSS Transitions and Animations
div:hover {
width: 300px;
}
Example 2:
style.css
div {
width: 100px;
height: 100px;
color: white;
background: red;
transition: width 2s, height 4s, transform 2s;
}
div:hover {
width: 300px;
height: 300px;
transform: skewX(50deg);
}
0.1.2 Transition Delay
The “ transition-delay ” property specifies a delay (in seconds) for the
transition effect.
Example:
style.css
div {
width: 100px;
height: 100px;
color: white;
background: red;
transition: width 2s, height 4s;
transition-delay: 1s;
}
div:hover {
width: 300px;
height: 300px;
}
div:hover {
width: 300px;
height: 300px;
}
@keyframes my-animation {
from {
background-color: red;
}
to {
background-color: yellow;
}
}
div {
width: 100px;
height: 100px;
background-color: green;
animation-name: my-animation;
animation-duration: 4s;
}
0.2.2 Multiple Keyframes
It is also possible to use percentages from 0% to 100% like this.
Example:
style.css
@keyframes my-animation {
0% {
background-color: red;
}
25% {
background-color: yellow;
}
50% {
background-color: blue;
}
100% {
background-color: green;
}
}
div {
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
}
0.2.3 Animation Delay
The “ animation-delay ” property specifies a delay for the start of an
animation.
Example:
style.css
@keyframes my-animation {
0% {
background-color: red;
}
25% {
background-color: yellow;
}
50% {
background-color: blue;
}
100% {
background-color: green;
}
}
div {
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-delay: 2s;
}
0.2.4 Animation Iteration Count
The “ animation-iteration-count ” property specifies the number of times
an animation should run. We can set its value to a number or " infinite " (the
animation continue forever).
Example:
style.css
@keyframes my-animation {
0% {
background-color: red;
}
25% {
background-color: yellow;
}
50% {
background-color: blue;
}
100% {
background-color: green;
}
}
div {
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-iteration-count: 3;
}
0.2.5 Animation Direction
The “ animation-direction ” property lets an animation run in reverse
direction or alternate cycles.
Example 1:
style.css
@keyframes my-animation {
from {
left: 0;
}
to {
left: 300px;
}
}
div {
position: relative;
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-iteration-count: 3;
animation-direction: reverse;
}
Result: The box is moved from the right ( left: 300px ) to the left ( left:
0 ) three times.
Example 2:
style.css
@keyframes my-animation {
from {
left: 0;
}
to {
left: 300px;
}
}
div {
position: relative;
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-iteration-count: 3;
animation-direction: alternate;
}
Example:
style.css
@keyframes my-animation {
from {
left: 0;
}
to {
left: 300px;
}
}
div {
position: relative;
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-timing-function: ease-out;
}
0.2.7 Shorthand Animation Property
The “ animation ” property is the shorthand of the above animation
properties. For example:
style.css
div {
position: relative;
width: 100px;
height: 100px;
background-color: cyan;
animation-name: my-animation;
animation-duration: 4s;
animation-iteration-count: infinite;
animation-direction: alternate;
animation-timing-function: linear;
}
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<section>
<header>
<h2>This is a heading</h2>
</header>
<p>This is a paragraph.</p>
<footer>
<p>This is a footer.</p>
</footer>
</section>
<footer>
<p>This is the main footer.</p>
</footer>
</body>
</html>
style.css
:root {
--a-global-color: red;
}
section {
--a-local-color: blue;
}
header {
color: var(--a-global-color);
}
footer {
color: var(--a-local-color);
}
Example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>Header</header>
<div class="main-content">
<p>This is a paragraph</p>
<p class="long-content">This is a long paragraph</p>
</div>
<footer>Footer</footer>
</body>
</html>
style.css
header,
footer {
height: 30px;
line-height: 30px;
}
header {
border-bottom: 1px solid black;
}
footer {
border-top: 1px solid black;
text-align: center;
}
.main-content {
min-height: calc(100vh - 96px);
}
.long-content {
border: 1px solid #ccc;
/* height: 1000px; */
}
Open this web page in a browser and try to change the height of the
browser; you will see that <footer> is always at the bottom of the page.
Then, uncomment the CSS “ height ” property of the <p class="long-
content"> element to see that the code still works well with long content.
1.3 CSS Counters
The CSS counter helps us create automatic numbering outlines without
any JavaScript code.
● counter-reset - Creates a counter by giving it a name
● counter-increment - Increments a counter value
<h1>Scripting tutorials:</h1>
<h2>JavaScript</h2>
<h2>VBScript</h2>
</body>
</html>
style.css
body {
font-size: 12px;
counter-reset: my-section;
}
h1 {
counter-reset: my-sub-section;
}
h1::before {
counter-increment: my-section;
content: "Section " counter(my-section) ". ";
}
h2::before {
counter-increment: my-sub-section;
content: counter(my-section) "." counter(my-sub-section) " ";
}
Result:
CHAPTER 22
Responsive CSS
The columns inside a row are all floating to the left. Therefore, when a
row does not use all its columns, other elements behind it or from the next
row could be placed to fill that unused space. To prevent this, we will add a
style that clears the flow.
.row::after {
content: "";
clear: both;
display: block;
}
.row::after {
content: "";
clear: both;
display: block;
}
style.css
.row div {
padding: 8px;
border: 1px solid black;
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<link rel="stylesheet" href="rwd-grid.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="row">
<div class="col-3 col-m-3">DIV 1</div>
<div class="col-6 col-m-9">DIV 2</div>
<div class="col-3 col-m-12">DIV 3</div>
</div>
</body>
</html>
Result:
For mobiles having a screen width smaller than 600px, the style
[class*="col-"] will be applied.
1 2 3 4 5 6 7 8 9 10 11 12
DIV 1
DIV 2
DIV 3
For tablets having screen widths between 600px and 768px, styles of
col-m-3, col-m-9 and col-m-12 will be applied since they override the
style [class*="col-"] .
1 2 3 4 5 6 7 8 9 10 11 12
DIV 1 DIV 2
DIV 3
For desktops with a screen width larger than 768px, col-3 and col-6
will be applied since they override the style [class*="col-"] .
1 2 3 4 5 6 7 8 9 10 11 12
DIV 1 DIV 2 DIV 3
2.5 Mobile-first vs. Desktop-first
2.5.1 Mobile-First
Mobile-first responsive CSS is designed/written for smaller screen-size
first. It will make the page display faster on smaller devices.
Mobile-first uses the “ min-width ” property in the media query so that
the CSS inside it is only calculated when the screen size is bigger than the
“ min-width .”
The example in the section “RWD Grid View” is mobile-first.
Therefore, as in the screenshot, the browser only proceeds with a few CSS
lines of code on a small device.
However, if we use a bigger device, more CSS must have proceeded, as
shown in the below screenshot.
2.5.2 Desktop-First
Desktop-first responsive CSS is designed/written for bigger screen size
first. It will make the page display faster on bigger devices.
Desktop-first uses“ max-width ” property in the media query so that the
CSS inside it is only calculated when the screen size is smaller than the
“ max-width .”
For example, let’s change the CSS code of the “RWD Grid View” to be
desktop-first.
rwd-grid.css
*{
box-sizing: border-box;
}
.row::after {
content: "";
clear: both;
display: block;
}
[class*="col-"] {
float: left;
}
/* For desktop: */
.col-1 { width: 8.33%; }
.col-2 { width: 16.66%; }
.col-3 { width: 25%; }
.col-4 { width: 33.33%; }
.col-5 { width: 41.66%; }
.col-6 { width: 50%; }
.col-7 { width: 58.33%; }
.col-8 { width: 66.66%; }
.col-9 { width: 75%; }
.col-10 { width: 83.33%; }
.col-11 { width: 91.66%; }
.col-12 { width: 100%; }
Thank you for purchasing and reading my book. Please leave a review on
Amazon after reading this book.
This page has been left blank intentionally.
Please turn it over.
About the Author
Neo D. Truman has been using computers since 1998, when he was a
child. In 2011, he got a Master of Science in Information Technology
degree. Neo has more than 15 years of experience in software development,
especially full-stack web development.
Other Books by The Author