Creating Responsive Websites Using Html5 Css3
Creating Responsive Websites Using Html5 Css3
Websites Using
HTML5 and CSS3
A Perfect Reference for Web Designers
—
Varun Gor
Creating Responsive
Websites Using
HTML5 and CSS3
A Perfect Reference for
Web Designers
Varun Gor
Creating Responsive Websites Using HTML5 and CSS3: A Perfect Reference
for Web Designers
Varun Gor
Bengaluru, India
Acknowledgments�����������������������������������������������������������������������������xix
v
Table of Contents
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
ix
Table of Contents
Scaling���������������������������������������������������������������������������������������������������������166
Rotation�������������������������������������������������������������������������������������������������������167
Skewing�������������������������������������������������������������������������������������������������������167
Origin Manipulation�������������������������������������������������������������������������������������168
Combining Transformations�������������������������������������������������������������������������168
CSS3 3D Transformations���������������������������������������������������������������������������������169
Understanding CSS3 3D Transformations����������������������������������������������������169
Key Concepts of CSS3 3D Transformations�������������������������������������������������169
Summary����������������������������������������������������������������������������������������������������������172
x
Table of Contents
xi
Table of Contents
Radio Input��������������������������������������������������������������������������������������������������233
File Input������������������������������������������������������������������������������������������������������234
Search Input������������������������������������������������������������������������������������������������236
Range Input�������������������������������������������������������������������������������������������������237
Submit Input������������������������������������������������������������������������������������������������238
Reset Input��������������������������������������������������������������������������������������������������239
Button Input�������������������������������������������������������������������������������������������������239
Polyfill Nonsupportive Browsers�����������������������������������������������������������������������240
Summary����������������������������������������������������������������������������������������������������������242
xii
Table of Contents
Index�������������������������������������������������������������������������������������������������265
xiii
About the Author
Varun Gor has more than 14 years of
experience creating websites using Java,
HTML, CSS, and JavaScript technologies and
has worked with major IT companies with
global clienteles. Varun graduated with a
degree in computer science from Visvesvaraya
Technological University in 2007 and has
been part of the corporate world ever since.
Alongside his innate nature to explore
technology, Varun is interested in outdoor activities; he has been part of
club cricket and played division 3 league matches, been on a night trek
near Bengaluru, and explored the city (less city more food) on his bike. In
addition, he enjoys binge-watching good movies and TV shows (recently
on web series), and at times he disconnects himself from the world around
him using a device named headphones. Recently he has been trying his
hand at cooking (God save his family).
xv
About the Technical Reviewer
Sourabh Mishra is an entrepreneur,
developer, speaker, author, corporate trainer,
and animator. He is a Microsoft guy; he is
passionate about Microsoft technologies
and a true .NET warrior. Sourabh has loved
computers from childhood and started his
career when he was just 15 years old. His
programming experience includes C/C++,
ASP.NET, C#, VB.NET, WCF, SQL Server, Entity Framework, MVC, Web
API, Azure, jQuery, Highcharts, and Angular. He is also an expert in
computer graphics. Sourabh is the author of Practical Highcharts with
Angular, published by Apress. Sourabh has been awarded a Most Valuable
Professional (MVP) status. He has the zeal to learn new technologies,
sharing his knowledge on several online community forums.
He is a founder of IECE Digital and Sourabh Mishra Notes, an online
knowledge-sharing platform where one can learn new technologies easily
and comfortably.
xvii
Acknowledgments
First I would like to acknowledge my mother, wife, and brother who
supported me in this venture and believed that I could do something I
never thought was possible for me. I also acknowledge the guidance of my
mentors who have shaped my career in the field of IT.
I would also like to acknowledge the Apress team, particularly Divya
Modi and Shonmirin P.A., who went through the trouble of chasing down
every minute detail and helping me shape this book. This was a tough time
for them, and this book would have not been possible without them.
A special acknowledgment goes to my two furry friends, Coco and Arlo.
The way they light up the surroundings has made it easy for me (actually
everyone) to complete this book.
xix
CHAPTER 1
Introduction to Web
Development
This chapter will cover why web development is needed in today’s digital
world, how web development is done, and which technologies are capable
of creating world-class and high-performing websites. Web developers
need to know how HTML and CSS work, which will be covered in depth.
I will briefly explain HTML elements and page structure so you can
understand how HTML and CSS work in conjunction to create websites. I
will also explain the problem that CSS solves and how to write CSS code.
2
Chapter 1 Introduction to Web Development
3
Chapter 1 Introduction to Web Development
4
Chapter 1 Introduction to Web Development
5
Chapter 1 Introduction to Web Development
The rendering engine is the part of the browser that takes the HTML,
CSS, and JavaScript code and turns it into a visual representation on the
screen. It parses the HTML and constructs a document object model
(DOM), which is a treelike structure that represents the content and
structure of the web page (Figure 1-2). The rendering engine then uses the
DOM and CSS to determine how the web page should be displayed.
6
Chapter 1 Introduction to Web Development
7
Chapter 1 Introduction to Web Development
HTML Elements
HTML elements are the building blocks of web pages, and they define
the structure and content of the page. Each HTML element is surrounded
by opening and closing tags, which tell the browser how to display the
content. Though almost all of the tags have opening and closing tags, e.g.,
<tag_name></tag_name>, some tags have just the opening tag like <img>,
<hr/>, etc. We are going to take a look at various HTML elements that are
used to create web pages.
HTML elements can be categorized into several groups based on
their function. Some of the most common categories include structural
elements, text elements, multimedia elements, form elements, and
scripting elements.
Structural Elements
Structural elements are used to define the overall structure of the web page.
They include elements such as the <html>, <head>, <title>, and <body>
tags. The <html> tag is used to define the document type, while the <head>
tag contains information about the document, such as the title, author, and
description. The <body> tag contains the main content of the web page.
8
Chapter 1 Introduction to Web Development
Text Elements
Text elements are used to add text content to the web page. They include
elements such as the <p>, <h1>–<h6>, and <em> tags. The <p> tag is used
to create paragraphs, while the <h1>–<h6> tags are used to create headings
of different sizes. The <em> tag is used to emphasize text, while the
<strong> tag is used to highlight important text.
Here is an example of a heading tag:
<html>
<body>
<h1>This text is Heading 1.</h1>
<h2>This text is Heading 2.</h2>
<h3>This text is Heading 3.</h3>
<h4>This text is Heading 4.</h4>
<h5>This text is Heading 5.</h5>
<h6>This text is Heading 6.</h6>
</body>
</html>
9
Chapter 1 Introduction to Web Development
<html>
<body>
<p>
This paragraph is written inside <p> element.
It will be displayed as continous text in the
browser.
Let us see how does it look on the browser.
</p>
</body>
</html>
Multimedia Elements
Multimedia elements are used to add multimedia content to the web page,
such as images and videos. They include elements such as the <img> and
<video> tags. The <img> tag is used to display images, while the <video>
tag is used to display videos.
Here is a code example for <img>:
<html>
<body>
<img src="../../../html dom.jpg" alt="dom image">
</body>
</html>
10
Chapter 1 Introduction to Web Development
Form Elements
Form elements are used to create forms on the web page, which allow
users to input information. They include elements such as the <form>,
<input>, and <button> tags. The <form> tag is used to create the form,
while the <input> tag is used to create input fields for the user to enter
information. The <button> tag is used to create buttons that the user can
click to submit the form. We are going to take a deeper look at the form
elements later in this book.
11
Chapter 1 Introduction to Web Development
Scripting Elements
Scripting elements are used to add interactivity to the web page, such as
animations and user interface elements. They include elements such as
the <script> and <canvas> tags. The <script> tag is used to add JavaScript
code to the web page, while the <canvas> tag is used to create graphics and
animations. We will learn about scripts and animation in later chapters.
In addition to these categories, there are many other HTML elements
that can be used to create web pages. Some of these elements are used
for more specialized purposes, such as the <audio> tag for playing audio
files or the <iframe> tag for embedding external web pages within the
current page.
It’s important to note that HTML elements are not the only component
of a web page. Cascading Style Sheets and JavaScript are also used to
define the visual appearance and interactivity of the page, respectively.
However, HTML elements provide the foundation for the page and define
its overall structure and content.
In conclusion, HTML elements are the building blocks of web pages.
They define the structure and content of the page, and they are used to
create everything from text to multimedia to forms and interactivity. By
understanding the different types of HTML elements and how they are
used, web developers can create rich and engaging web pages that are easy
to navigate and interact with.
12
Chapter 1 Introduction to Web Development
13
Chapter 1 Introduction to Web Development
14
Chapter 1 Introduction to Web Development
p {
font-family: Arial;
font-size: 22px;
color: #bb0d10;
}
HTML Code:
<html>
<body>
<p>
The properties font-family, font-size, and color
are then defined, which set the font, font size,
and color of the text within the paragraph element.
</p>
<link rel="stylesheet" href="../../css/example.css">
</body>
</html>
15
Chapter 1 Introduction to Web Development
Figure 1-6. CSS applied the font color for the <p> element
In this example, the p selector targets all <p> elements in the HTML
file. The properties font-family, font-size, and color are then defined, which
set the font, font size, and color of the text within the paragraph element.
CSS works by flowing styles down from the parent element to its
children. This means that if a style is defined for a parent element, it will be
inherited by its child elements unless a different style is explicitly defined.
For example, if a style is defined for the <body> element of a page, all
elements within the body will inherit that style unless a different style is
specified.
In addition to being cascading, CSS uses specificity to determine which
styles should be applied to an element. Specificity refers to the weight or
importance of a style rule. Styles with a higher specificity will override
styles with a lower specificity. Specificity is determined by a combination
of selectors, with more specific selectors taking precedence over less
specific ones.
For example, a style rule that targets a specific ID will have a higher
specificity than a rule that targets a class or element. The following
example demonstrates this:
#header {
background-color: blue;
}
16
Chapter 1 Introduction to Web Development
.header {
background-color: red;
}
<html>
<body>
<h1 id="header" class="header">This text is
Heading 1.</h1>
<link rel="stylesheet" href="../../css/example.css">
</body>
</html>
As shown in Figure 1-7, the style rule that targets the #header ID will be
applied, even though the .header class rule comes later in the file.
17
Chapter 1 Introduction to Web Development
18
Chapter 1 Introduction to Web Development
19
Chapter 1 Introduction to Web Development
CSS Selectors
CSS selectors are a powerful feature of Cascading Style Sheets that allow
developers to target specific elements on a web page and apply styles to
them. CSS selectors make it possible to create unique and complex styles
for different elements and are an essential tool for creating effective and
engaging web designs. In this section, we will explore the basics of CSS
selectors and how they work.
CSS selectors are used to target specific elements on a web page, such
as headings, paragraphs, links, and images. Selectors can be used to apply
styles to individual elements or to groups of elements. There are several
types of CSS selectors; each has its own syntax and functionality.
• Type selectors: Type selectors target elements based
on their HTML tag name. For example, the selector h1
would target all heading level 1 elements on the page.
Type selectors are the simplest type of selector and are
often used to apply global styles to all elements of a
particular type.
20
Chapter 1 Introduction to Web Development
CSS selectors are an essential tool for web developers, as they allow
for precise targeting of specific elements on a web page. By using a
combination of type selectors, class selectors, ID selectors, attribute
selectors, pseudo-classes, and pseudo-elements, developers can
21
Chapter 1 Introduction to Web Development
create unique and complex styles for different elements on a web page.
Understanding CSS selectors is a fundamental aspect of web development
and is essential for creating effective and engaging web designs. All these
selectors will be covered as part of later chapters.
Summary
This chapter covered the technologies used in web development. It
also covered how HTML is rendered by a browser and its DOM tree, the
different HTML elements, and the way it is being displayed by the browser
using pseudo-code. It covered HTML page structure and how it can be
defined in multiple ways. We also looked at how CSS works along with
HTML and what kinds of problems can be solved using CSS and different
CSS selectors.
22
CHAPTER 2
HTML5 and
Responsive Web
Design
This chapter covers HTML5 and responsive web design by describing
the features that are supported by modern-day browsers. It covers how
to create an HTML5 page and explains why it is easier to write pages with
HTML5 than its older versions. The chapter also covers semantic elements
and shows the code to make it easier to understand the practical usage.
Additionally, the chapter explains text-level semantics in detail, followed
by the audio and video capabilities. All these concepts are supported by
code examples and browser screenshots displaying how a modern-day
browser renders the code.
a new feature, you should always check the browser version your app is
going to run on. Here are some of the commonly used HTML5 features
that are widely supported across all modern browsers:
24
Chapter 2 HTML5 and Responsive Web Design
25
Chapter 2 HTML5 and Responsive Web Design
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=UTF-8" />
Save the previous code with an .html extension, and you have
written your first HTML5 page according to the W3C validator (http://
validator.w3.org)!
26
Chapter 2 HTML5 and Responsive Web Design
The first line of the code declares the new HTML5 doctype; remember,
<!DOCTYPE html> and <!doctype html> are the same; the case does not
make any difference.
The second tag is the first <html> tag, which mentions the language.
<html lang="en">
HTML5 does not require so many details; it will just work fine with the
following declaration:
If you look closely, there is no ending tag or closing slash, there are
no quotes surrounding attribute values, and there is no type declaration
either. Here both the examples are valid and would work just fine.
27
Chapter 2 HTML5 and Responsive Web Design
<div id=wrapper>
This HTML code is a valid <img> tag without an end tag or a slash,
without quotes, and with mixing upper and lowercase. HTML even lets
developers write code without specifying <html>, <body>, and <head>
tags, and it still validates.
Although HTML5 is flexible, I still recommend writing a few extra lines
of code to maintain best practices for better code maintainability and ease
of understanding. Hence, writing code in the old style is beneficial. The
CSS declaration shown earlier, for example, can be written as follows:
The quotes and closing slash are in the stylesheet declaration, but the
type attribute is omitted here. This HTML code would not be flagged.
The anchor tag has been revised and can do a few things that the prior
version of HTML didn’t support. The older HTML version needed each
element to have its own anchor tag.
For example, look at the following code snippet:
HTML5 now allows us to group all the elements under the anchor tag,
and it doesn’t require each element to have its own anchor tag. See the
following code snippet:
28
Chapter 2 HTML5 and Responsive Web Design
<a>
<div class="container"> Home </div>
<p> This paragraph is actually a link tagged by
anchor. </p>
<h1> Navigate to Home Page </h1>
</a>
The only restriction here with the anchor tag is that it cannot be
grouped with another anchor tag, and form elements are not allowed to be
grouped within the anchor tag.
There are some features of HTML5 that are obsolete; it won’t complain
if you use them, but you should avoid using them if you can. The HTML5
validator will generate warnings for these elements.
There are two types of obsolete features: conforming and
nonconforming. The prior definition was for the conforming obsolete
feature, whereas a nonconforming obsolete feature doesn’t guarantee that
it will work on all the browsers. It may work on a few but not others, so you
should implement those types at your own risk. Here is where you can find
a list of nonconforming obsolete features: https://html.spec.whatwg.
org/#non-conforming-features.
29
Chapter 2 HTML5 and Responsive Web Design
<header></header>
<section>
<article>
<figure>
<img>
<figcaption></figcaption>
</figure>
</article>
</section>
<footer></footer>
<div id="header"></div>
<div class="section">
<div class="article">
<div class="figure">
<img>
<div class="figcaption"></div>
</div>
</div>
</div>
<div id="footer"></div>
30
Chapter 2 HTML5 and Responsive Web Design
<style>
.superheros {
margin: 0;
padding: 5px;
background-color: lightgray;
}
.superhero {
background: white;
}
31
Chapter 2 HTML5 and Responsive Web Design
Figure 2-2 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia).
32
Chapter 2 HTML5 and Responsive Web Design
<style>
aside {
width: 30%;
padding-left: 15px;
margin-left: 15px;
float: right;
font-style: italic;
background-color: lightgray;
}
</style>
<p>
Marvel Comics is an American comic book publisher
and the flagship property of Marvel Entertainment,
a division of The Walt Disney Company since
September 1, 2009. Evolving from Timely Comics
in 1939,
33
Chapter 2 HTML5 and Responsive Web Design
Figure 2-3 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia).
34
Chapter 2 HTML5 and Responsive Web Design
<style>
details > summary {
padding: 4px;
width: 200px;
background-color: #5296ce;
border: none;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;
}
details > p {
background-color: #5296ce;
padding: 4px;
margin: 0;
35
Chapter 2 HTML5 and Responsive Web Design
<details>
<summary>
ICC World Cup
</summary>
<p>
The Cricket World Cup, officially known
as ICC Men's Cricket World Cup,[4] is the
international championship of
One Day International (ODI) cricket. The event
is organised by the sport's governing body, the
International Cricket Council
(ICC), every four years, with preliminary
qualification rounds leading up to a finals
tournament. The tournament is one of the
world's most viewed sporting events and
is considered the "flagship event of the
international cricket calendar" by the ICC.[5]
36
Chapter 2 HTML5 and Responsive Web Design
Figure 2-3 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia). Figure 2-4 shows the HTML <details> tag
expanded.
37
Chapter 2 HTML5 and Responsive Web Design
<style>
figure {
border: 1px #cccccc solid;
padding: 4px;
margin: auto;
}
figcaption {
background-color: black;
color: white;
font-style: italic;
padding: 2px;
text-align: center;
}
</style>
<figure>
<img src="../../../cityscape.jpeg" alt="cityscape"
style="width: 100%; height: 90%;" />
<figcaption>High rise buildings in the city at
night look so amazing.</figcaption>
</figure>
38
Chapter 2 HTML5 and Responsive Web Design
<style>
footer {
text-align: center;
padding: 3px;
background-color: DarkSalmon;
color: white;
}
</style>
<footer>
<p>Author: John Doe<br>
<a href="mailto:[email protected]">
[email protected]</a>
</p>
</footer>
39
Chapter 2 HTML5 and Responsive Web Design
Note The footer is placed after the figcaption tag and shows the
author information.
<style>
header {
display: block;
}
</style>
40
Chapter 2 HTML5 and Responsive Web Design
<header>
<h1>Main page heading here</h1>
<p>Posted by John Doe</p>
</header>
<style>
figure {
border: 1px #cccccc solid;
padding: 4px;
margin: auto;
}
figcaption {
background-color: black;
color: white;
font-style: italic;
padding: 2px;
text-align: center;
}
</style>
<figure>
<img src="../../../cityscape.jpeg" alt="cityscape"
style="width: 100%; height: 90%;" />
<figcaption>High rise buildings in the city at
night look so amazing.</figcaption>
</figure>
41
Chapter 2 HTML5 and Responsive Web Design
<hgroup>
<h1>Heading H_One</h1>
<h2>Heading H_Two</h2>
<hgroup>
<p>This is a sample text in paragraph 1.</p>
<p>This is a sample text in paragraph 2.</p>
<p>This is a sample text in paragraph 3.</p>
<p>This is a sample text in paragraph 4.</p>
</body>
42
Chapter 2 HTML5 and Responsive Web Design
<style>
main {
margin: 0;
padding: 5px;
background-color: rgb(91, 153, 161);
}
43
Chapter 2 HTML5 and Responsive Web Design
.cricketer {
background: rgb(137, 116, 116);
}
44
Chapter 2 HTML5 and Responsive Web Design
Figure 2-9 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia).
45
Chapter 2 HTML5 and Responsive Web Design
<style>
mark {
background-color: yellow;
color: black;
}
</style>
<p>Send <mark>bug report</mark>, holiday plan and
<mark>MOM</mark> to the higher management.</p>
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/python/">Python</a>
</nav>
46
Chapter 2 HTML5 and Responsive Web Design
<style>
section {
display: block;
}
</style>
<section>
<h2>WWF History</h2>
<p>The World Wide Fund for Nature (WWF) is an
international organization working on issues
regarding the conservation, research and
restoration of the environment, formerly named the
World Wildlife Fund. WWF was founded in 1961.</p>
</section>
<section>
<h2>WWF's Symbol</h2>
<p>The Panda has become the symbol of WWF. The
well-known panda logo of WWF originated from a
panda named Chi Chi that was transferred from the
Beijing Zoo to the London Zoo in the same year of
the establishment of WWF.</p>
</section>
47
Chapter 2 HTML5 and Responsive Web Design
Figure 2-12 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia).
<style>
address {
display: block;
font-style: italic;
}
</style>
<p>
The properties font-family, font-size, and color
are then defined, <br/>
which set the font, font size, <br/>
and color of the text within the paragraph element.
48
Chapter 2 HTML5 and Responsive Web Design
<br/><br/>
The stylesheet is applied because it has been
defined for element <p> in <br/>
parent folder and file example.css.
</p>
<link rel="stylesheet" href="../../css/example.css">
<address>
Written by <a href="mailto:[email protected]">Jon
Doe</a>.<br>
Visit us at:<br>
Example.com<br>
Box 564, Disneyland<br>
USA
</address>
Figure 2-13 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia)..
49
Chapter 2 HTML5 and Responsive Web Design
<style>
details > summary {
padding: 4px;
width: 200px;
background-color: #d9b37c;
border: none;
box-shadow: 1px 1px 2px #131313;
cursor: pointer;
}
details > p {
background-color: #d9b37c;
padding: 4px;
margin: 0;
box-shadow: 1px 1px 2px #131313;
}
</style>
<details>
<summary>Marvel Comics</summary>
<p>
Marvel Comics is an American comic book
publisher and the flagship property of Marvel
Entertainment,
a division of The Walt Disney Company since
September 1, 2009. Evolving from Timely Comics
in 1939,
Magazine Management/Atlas Comics in 1951 and
its predecessor, Marvel Mystery Comics, the
Marvel Comics title/name/brand
was first used in June 1961.
50
Chapter 2 HTML5 and Responsive Web Design
51
Chapter 2 HTML5 and Responsive Web Design
52
Chapter 2 HTML5 and Responsive Web Design
<style>
abbr {
display: inline;
}
</style>
<p><dfn><abbr title="Cascading Style Sheets">CSS</abbr>
</dfn> is a language that describes the style of an
HTML document.</p>
53
Chapter 2 HTML5 and Responsive Web Design
<style>
q {
color: gray;
font-style: italic;
}
</style>
<p>WWF's goal is to:
<q>Build a future where people live in harmony with
nature.</q>
We hope they succeed.
</p>
54
Chapter 2 HTML5 and Responsive Web Design
<style>
cite {
font-style: italic;
color: rgb(126, 126, 237);
}
</style>
<p><cite>The sport of cricket</cite> has a known
history beginning in the late 16th century. Having
originated in south-
east England,
it became an established sport in the country in
the 18th century and developed globally in the 19th
and 20th centuries.
International matches have been played since the
19th-century and formal Test cricket matches are
considered to date from 1877.</p>
Figure 2-19 shows what it looks like in a browser (the paragraph in the
code is taken from Wikipedia).
55
Chapter 2 HTML5 and Responsive Web Design
For example, the <mark> element can be used to indicate the location
of a particular point within the text. This can be particularly useful for
people with visual impairments, who may find it difficult to navigate
through large blocks of text.
Similarly, the <abbr> element can be used to provide additional
context and information about the meaning of a particular word or phrase.
This can be particularly useful for people with cognitive disabilities, who
may have difficulty understanding certain words or concepts.
In addition to improving accessibility, text-level semantics can also
improve the search engine optimization of a web page. By providing
additional context and information about the content of a page, these
elements make it easier for search engines to understand and index the
content, which can lead to better search engine rankings and increased
traffic to the site.
56
Chapter 2 HTML5 and Responsive Web Design
<!DOCTYPE html>
<html>
<body>
<video width="1080" height="720" controls>
<source src="../../../sample.mp4" type=video/mp4>
</video>
</body>
</html>
57
Chapter 2 HTML5 and Responsive Web Design
• type: The video file format that will be used to play the
content.
Additionally, the following are option controls that help influence the
video content:
mp4 video/mp4
webm video/webm
ogg video/ogg
58
Chapter 2 HTML5 and Responsive Web Design
<!DOCTYPE html>
<html>
<body>
<h2>Steve Jobs - How to Live before You Die</h2>
<p>At his Stanford University commencement speech, Steve
Jobs, CEO and co-founder of Apple and Pixar, urges us to
pursue our dreams and see the opportunities in life's
setbacks - including death itself.</p>
<iframe width="500" height="320" src="https://www.youtube.
com/embed/lcZDWo6hiuI">
</iframe>
</body>
</html>
The <audio> tag can be used to embed an audio file in the web page. Just
like the <video> tag, the <audio> tag has the controls and source attributes
that identify the file and whether to show the controls on the web page.
Here is what it looks like in code:
mp3 audio/mpeg
wav audio/wav
ogg audio/ogg
Summary
This chapter covered the features of HTML5 that can be used to create a
responsive web design. It explained the new features supported by this
technology and listed the features such as the semantics, audio, and video
capabilities added to HTML, as well as the canvas, geolocation, local
storage, web works, and web sockets. We also explained how to write a new
HTML5 web page, ways to make the job easier, and new features added
to HTML5.
60
CHAPTER 3
Cascading Style
Sheets and Layouts
This chapter covers CSS and layouts. This chapter will explain how to
create and use floats in CSS3, as well as explaining the issues faced when
working with floats and how to resolve them. Next, the chapter will cover
box-sizing versus border-box, which one to use, and how to resolve issues
if there are any during implementing them. Then, the chapter will explain
how to implement a flexbox layout using CSS3, by providing HTML and
CSS code and showing how the browser renders this code. It will explain
various attributes and their values as well as how to arrange flex items
and what properties they can have. The CSS grid layout is the next topic,
covering details such as aligning and spacing grid items and sizing each
item in the layout.
• Flexbox
• Grid
62
Chapter 3 Cascading Style Sheets and Layouts
• Floats
Using Floats
The CSS3 float property allows you to position an element to the left or
right of its containing parent block, allowing other elements to flow around
it. What float does is take out the element from its normal document flow
and position it in relation to its parent element.
63
Chapter 3 Cascading Style Sheets and Layouts
<!DOCTYPE html>
<html>
<head>
<style>
/* The container div */
.container {
width: 600px;
margin: 0 auto;
background-color: cornsilk;
padding: 10px;
}
64
Chapter 3 Cascading Style Sheets and Layouts
<body>
<div class="container">
<div class="left">
<p>This is a left floated div.</p>
<p>Other elements will flow around it.</p>
</div>
<div class="right">
<p>This is a right floated div.</p>
<p>Other elements will flow around it.</p>
</div>
<p>This is some text that will flow around the floated
divs.</p>
</div>
</body>
</html>
This code example has a parent container <div> with two child <div>s;
the first one is floated to the left, and the second one is floated to the
right. We also have a paragraph element after the floated <div>s that flows
around them.
The .left and .right classes specify the float property, as well as the
width, background color, padding, and margin properties. The .container
class specifies the width, margin, background color, and padding
properties.
Note that when using floats, it is important to clear them afterward to
prevent unexpected layout behavior. This can be done by using the clear
property or by using a clearfix hack.
Figure 3-1 shows how the code is displayed in a browser.
65
Chapter 3 Cascading Style Sheets and Layouts
When working with CSS floats, it’s common to encounter issues where
floated elements do not behave as expected, such as when the containing
element doesn’t expand to contain its floated children or when subsequent
elements are unintentionally affected by the float.
CSS clearfix will come to rescue to fix this problem, which is a
technique to force a container element to expand and contain its floated
children. Let’s look at an example of how to use a clearfix.
Here is some code without the clearfix:
<!DOCTYPE html>
<html>
<head>
<style>
/* The container div with clearfix */
/*.container:after {
content: "";
display: table;
clear: both;
}*/
66
Chapter 3 Cascading Style Sheets and Layouts
67
Chapter 3 Cascading Style Sheets and Layouts
<!DOCTYPE html>
<html>
<head>
<style>
/* The container div with clearfix */
.container:after {
content: "";
display: table;
68
Chapter 3 Cascading Style Sheets and Layouts
clear: both;
}
69
Chapter 3 Cascading Style Sheets and Layouts
70
Chapter 3 Cascading Style Sheets and Layouts
<!DOCTYPE html>
<html>
<head>
<title>Float Layout Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<h2>Welcome to my website!</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed in ante vitae arcu vulputate suscipit sit
amet non massa. In hac habitasse platea dictumst. Sed
tempor elit a urna vulputate hendrerit. Proin vitae
massa non augue posuere bibendum. Nulla laoreet sodales
leo, vel egestas lorem feugiat at.</p>
71
Chapter 3 Cascading Style Sheets and Layouts
</main>
<footer>
<p>© 2023 My Website. All rights reserved.</p>
</footer>
</body>
</html>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
header {
background-color: #c73636;
padding: 20px;
}
nav {
float: left;
width: 20%;
background-color: aquamarine;
height: 500px;
}
nav ul {
list-style: none;
padding: 0;
margin: 0;
}
72
Chapter 3 Cascading Style Sheets and Layouts
nav li {
padding: 10px;
}
nav a {
text-decoration: none;
color: #333;
}
main {
float: none;
width: 100%;
background-color: wheat;
padding: 20px;
height: 460px;
}
footer {
clear: both;
background-color: #ccc;
padding: 20px;
color: #fff;
text-align: center;
}
73
Chapter 3 Cascading Style Sheets and Layouts
Box-Sizing or Border-Box
An element’s box-model size can be controlled by the box-sizing property
in CSS. By default, the size of an element is calculated based on its
content, padding, border, and margin. However, with box-sizing, you can
change this behavior to calculate the size of an element based on different
box models.
There are two values for the box-sizing property: content-box and
border-box.
74
Chapter 3 Cascading Style Sheets and Layouts
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
header {
background-color: #c73636;
padding: 20px;
}
nav {
float: left;
width: 200px;
background-color: aquamarine;
75
Chapter 3 Cascading Style Sheets and Layouts
height: 500px;
box-sizing: content-box;
}
nav ul {
list-style: none;
padding: 0;
margin: 0;
}
nav li {
padding: 10px;
}
nav a {
text-decoration: none;
color: #333;
}
main {
float: none;
width: 1000px;
background-color: wheat;
padding: 20px;
height: 460px;
}
footer {
clear: both;
background-color: #ccc;
padding: 20px;
color: #fff;
text-align: center;
}
76
Chapter 3 Cascading Style Sheets and Layouts
container {
width: 1200px;
}
<!DOCTYPE html>
<html>
<head>
<title>Float Layout Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body class="container">
<header>
<h1>My Website</h1>
</header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<main>
<h2>Welcome to my website!</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Sed in ante vitae arcu vulputate suscipit sit
amet non massa. In hac habitasse platea dictumst. Sed
tempor elit a urna vulputate hendrerit. Proin vitae
massa non augue posuere bibendum. Nulla laoreet sodales
leo, vel egestas lorem feugiat at.</p>
</main>
77
Chapter 3 Cascading Style Sheets and Layouts
<footer>
<p>© 2023 My Website. All rights reserved.</p>
</footer>
</body>
</html>
Figure 3-5 shows how it looks in a browser (the paragraph comes from
https://loremipsum.io/).
Observe that the nav width of 200px and padding of 100px is added to
the box and the nav content is out of place.
Let’s use border-box and check how Google Chrome displays it; here
box-sizing: border-box in nav css definition is changed. See Figure 3-6.
78
Chapter 3 Cascading Style Sheets and Layouts
Introduction to Flexboxes
CSS3 has brought a lot of exciting new features to the field of web
development, and one of the most powerful is the flexbox layout system. A
flexbox, which means “flexible box layout,” is a flexible and easy-to-
use system for laying out elements in a container. It allows you to control
the alignment, size, and distribution of elements with just a few simple
properties, making it an essential tool for creating modern, responsive web
designs.
One of the key benefits of a flexbox is its simplicity. With just a few lines
of CSS, you can create complex and flexible layouts that would be difficult
or impossible with traditional CSS layout techniques. To create a flexbox,
a container element that encapsulates all the elements you want to lay out
needs to be created. By changing the display property value to flex (display:
flex), any HTML element can be turned into a flex container; let that HTML
element be a <div> or a section.
79
Chapter 3 Cascading Style Sheets and Layouts
Once you have your container set up, you can start using the various
flexbox properties to control the layout of the elements inside it. Some
of the most important properties include flex-direction, justify-content,
align-items, and flex-wrap.
80
Chapter 3 Cascading Style Sheets and Layouts
Flexbox Overview
CSS has revolutionized the way web pages are designed and structured.
One of the most powerful CSS features is the flexbox, a layout model that
lets developers create flexible and responsive designs with ease. Whether
you’re an experienced web developer or just a beginner, understanding
the fundamentals of a flexbox is essential for building modern, dynamic
web interfaces. In this section, we will provide an overview of a flexbox,
exploring its core concepts and demonstrating how it can streamline your
CSS layouts.
81
Chapter 3 Cascading Style Sheets and Layouts
82
Chapter 3 Cascading Style Sheets and Layouts
83
Chapter 3 Cascading Style Sheets and Layouts
84
Chapter 3 Cascading Style Sheets and Layouts
• Flex item margins: You can also use regular CSS margin
properties to add space around individual flex items.
An alternate to this is gap, which can be applied to flex
container and will do the same job as margins.
85
Chapter 3 Cascading Style Sheets and Layouts
.container {
font-family: sans-serif;
background-color: bisque;
font-size: 34px;
/* Flexbox */
display: flex;
align-items: center;
justify-content: flex-start;
gap: 30px;
.element--1 {
align-self: flex-start;
background-color: yellowgreen;
}
.element--2 {
background-color: burlywood;
}
.element--3 {
background-color: turquoise;
height: 150px;
}
86
Chapter 3 Cascading Style Sheets and Layouts
.element--4 {
background-color: springgreen;
}
.element--5 {
align-self: stretch;
order: 1;
background-color: slategray;
}
HTML file:-
<!DOCTYPE html>
<html>
<head>
<title>Float Layout Example</title>
<link rel="stylesheet" type="text/css"
href="style.css">
</head>
<body>
<div class="container">
<div class="element--1">1</div>
<div class="element--2">2</div>
<div class="element--3">3</div>
<div class="element--4">4</div>
<div class="element--5">5</div>
</div>
</body>
</html>
87
Chapter 3 Cascading Style Sheets and Layouts
Properties of Flex
In CSS, the flex property is a shorthand property that combines three
individual properties: flex-grow, flex-shrink, and flex-basis. It is used to
control the behavior and sizing of flex items within a flex container.
The flex property accepts up to three values.
88
Chapter 3 Cascading Style Sheets and Layouts
Here are a few examples of how the flex property can be used:
.flex-item {
flex: 1; /* Equivalent to flex-grow: 1, flex-shrink: 1,
flex-basis: 0 */
}
.flex-item {
flex: 0 0 200px; /* No growth, no shrinking, initial width
of 200 pixels */
}
.flex-item {
flex: 2 1 auto; /* Twice the growth compared to other
items, default shrinking, initial size based on content */
}
89
Chapter 3 Cascading Style Sheets and Layouts
By utilizing the flex property, you have control over how flex items
grow, shrink, and establish their initial size within a flex container.
<!DOCTYPE html>
<html>
<head>
<title>Float Layout Example</title>
<link rel="stylesheet" type="text/css"
href="style.css">
</head>
<body>
<div class="container">
<div class="el element--1">1</div>
<div class="el element--2">2</div>
<div class="el element--3">3</div>
<div class="el element--4">4</div>
<div class="el element--5">5</div>
</div>
</body>
</html>
.container {
font-family: sans-serif;
background-color: bisque;
font-size: 34px;
90
Chapter 3 Cascading Style Sheets and Layouts
/* Flexbox */
display: flex;
align-items: center;
justify-content: space-between;
gap: 30px;
.el {
flex: 1;
padding: 10px;
border: 1px solid #ccc;
}
.element--1 {
align-self: flex-start;
background-color: yellowgreen;
}
.element--2 {
background-color: burlywood;
}
.element--3 {
background-color: turquoise;
height: 150px;
}
.element--4 {
background-color: springgreen;
}
91
Chapter 3 Cascading Style Sheets and Layouts
.element--5 {
align-self: stretch;
order: 1;
background-color: slategray;
}
The flex container has three flex items in the previous code example.
The display property converts the normal container into a flex container.
The justify-content property is set to space-between, which places an
equal space between the items. The align-items property is set to center,
which vertically centers the items within the container.
The .item class has a flex property set to 1, which allows the items
to grow and shrink equally to fill the available space. We also add some
padding and styling to make the items visually distinguishable.
You can customize the layout by adjusting the flex properties and other
CSS properties to meet your specific needs. Feel free to modify the code as
desired.
Figure 3-8 shows how the code looks in a browser.
92
Chapter 3 Cascading Style Sheets and Layouts
93
Chapter 3 Cascading Style Sheets and Layouts
The CSS grid also offers powerful alignment and spacing options. You
can align elements vertically or horizontally within their respective grid
cells using properties such as justify-items, align-items, justify-content,
and align-content. These properties enable precise control over the
positioning of grid items. Furthermore, the grid-gap property allows you
to define the spacing between rows and columns, providing flexibility in
adjusting the overall grid layout.
One of the most powerful features of a CSS grid is its ability to handle
responsive design seamlessly. By utilizing media queries and the grid-
template-areas property, you can create different grid layouts for different
screen sizes. This flexibility makes it easier to build responsive websites
that adapt to various devices and screen resolutions.
The CSS grid is a game-changer for web layout design. With its intuitive
syntax and powerful capabilities, it simplifies the creation of grid-based
layouts, offers precise control over element positioning and alignment,
and enables seamless responsiveness. Whether you are a beginner or an
experienced developer, mastering the CSS grid layout opens up a world of
possibilities for creating modern and visually appealing web designs. So,
dive into CSS grid and elevate your web layout skills to the next level!
94
Chapter 3 Cascading Style Sheets and Layouts
Defining a Grid
To start using a CSS grid, we designate an element as the grid container
by applying the display: grid property. This establishes the grid context
for its child elements, turning them into grid items. Once the container is
defined, we can set up the rows and columns by using properties such as
grid-template-rows and grid-template-columns, specifying their sizes and
proportions or using keywords like auto to dynamically adjust based on
content.
95
Chapter 3 Cascading Style Sheets and Layouts
CSS grid introduces the concept of grid areas. With the grid-area property,
we can assign names to areas within the grid and easily position items in
those areas using the grid-area value.
Browser Support
A CSS grid enjoys widespread browser support, making it accessible to
a vast majority of web users. All the latest browsers, including Google
Chrome, Firefox, Safari, and Edge, have excellent support for CSS grids.
Additionally, with the use of vendor prefixes, developers can ensure
compatibility with older browser versions.
96
Chapter 3 Cascading Style Sheets and Layouts
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto 100px;
}
97
Chapter 3 Cascading Style Sheets and Layouts
• Using fixed sizes: To set fixed sizes for grid columns and
rows, we can use specific length units like pixels (px) or
any other appropriate unit. For instance:
.grid-container {
display: grid;
grid-template-columns: 200px 300px;
grid-template-rows: 100px 150px;
}
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr;
grid-template-rows: 1fr auto;
}
98
Chapter 3 Cascading Style Sheets and Layouts
.grid-container {
display: grid;
grid-template-columns: 1fr 200px 2fr;
grid-template-rows: auto 100px;
}
Here, the first column and the third column have flexible sizes that
adapt to the available space, while the middle column maintains a fixed
width of 200 pixels. The first row adjusts its height based on content, and
the second row has a fixed height of 100 pixels.
Sizing grid columns and rows in a CSS grid layout gives developers
fine-grained control over their web layouts. By combining fixed and
flexible sizes intelligently, we can create versatile and responsive grid-
based designs. Understanding the grid template and utilizing length units
like pixels and the fr unit empowers us to craft layouts that meet our design
goals. Experiment with different sizing techniques to achieve visually
appealing and adaptive grid layouts with a CSS grid.
99
Chapter 3 Cascading Style Sheets and Layouts
Here’s an example:
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: auto 100px;
}
Here’s an example:
.grid-item {
grid-column: 2 / 4; /* Starts at the 2nd column
line and ends at the 4th column line */
grid-row: 1; /* Starts at the 1st row line and ends
at the 1st row line (same row) */
}
Here’s an example:
.grid-item {
grid-area: header; /* Refers to a named grid area
called "header" */
}
100
Chapter 3 Cascading Style Sheets and Layouts
Here’s an example:
.grid-item {
justify-self: center; /* Centers the item
horizontally within its cell */
align-self: end; /* Aligns the item to the bottom
of its cell */
}
Here’s an example:
.grid-container {
justify-items: center; /* Centers all items
horizontally within their cells */
align-items: stretch; /* Stretches all items
vertically to fill their cells */
}
These are just a few examples of how you can place and align grid
items in a CSS grid layout. By combining these properties and values,
you can create various grid layouts and achieve precise control over the
positioning and alignment of your elements.
101
Chapter 3 Cascading Style Sheets and Layouts
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* Three columns with
equal width */
grid-gap: 10px; /* Gap between grid items */
}
.item {
background-color: #cd3434;
padding: 20px;
}
Here is grid.html:
<!DOCTYPE html>
<html>
<head>
<title>Float Layout Example</title>
<link rel="stylesheet" type="text/css"
href="style.css">
</head>
<body>
<div class="grid-container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
102
Chapter 3 Cascading Style Sheets and Layouts
103
Chapter 3 Cascading Style Sheets and Layouts
Summary
This chapter covered various topics related to CSS layouts and how to
implement them. We covered how to create and use floats, box-sizing,
and border-box. The chapter also covered flexboxes and how to create
them along with its attributes and their explanation. We talked about
the flex items in the flexbox layout and covered the properties of the flex.
We showed how to implement a CSS grid layout along with sizing grid
columns and rows and placing and aligning the grid items.
104
CHAPTER 4
Media Queries
In the era of smartphones, tablets, and multitudes of screen sizes, creating
a seamless user experience across devices has become crucial. Responsive
web design allows websites to adapt and respond to different viewport
sizes, providing optimal viewing experiences. CSS3 introduced a powerful
feature called media queries that enables developers to tailor stylesheets
based on various device characteristics. In this chapter, we will explore
what media queries are, how they work, and their significance in creating
responsive designs.
In this example, the styles within the curly braces will be applied when
the viewport width is 768 pixels or less. Media queries can also include
logical operators such as and, not, and only to combine multiple media
features for precise targeting.
106
Chapter 4 Media Queries
@media screen {
/* Styles for screen devices */
}
@media print {
/* Styles for print media */
}
107
Chapter 4 Media Queries
.container {
background-color: cadetblue;
width: 1920px;
height: 1080px;
clear: both;
}
108
Chapter 4 Media Queries
109
Chapter 4 Media Queries
<!DOCTYPE html>
<html>
<head>
<title>Media Query Example</title>
<link rel="stylesheet" type="text/css"
href="style.css">
</head>
<body>
<div class="container"></div>
</body>
</html>
How does Google Chrome display this with different resolution sizes?
See Figure 4-1 through Figure 4-4. (Note: As the browser size is changing,
the background color for <div> will change as defined in the CSS.)
110
Chapter 4 Media Queries
111
Chapter 4 Media Queries
112
Chapter 4 Media Queries
113
Chapter 4 Media Queries
The media query focuses on styling the web page based on the device’s
capabilities; in other words, if the device is able to load the styles, they will
be applied.
With this example, we have seen just one condition, max-width, but
media queries can work with a variety of other conditions. Loading a
device-specific (or conditional) CSS file is also possible, as shown here:
Note that, when used, this will be added to the HTTP request and may
affect the loading time of your web page.
When building media queries, most often the size and resolution of the
device are of primary focus, targeting the device’s viewport (the visible part
of the website for one particular device). However, media queries can be
tested with various parameters. As mentioned earlier, they can be tested
on width and height and device-width and device-height. In addition, the
aspect-ratio and color parameters can be tested. Most of the options can
be tested in a range by using the min and max options.
.container{
display: flex;
flex-direction: column;
height: 100vh;
114
Chapter 4 Media Queries
[class ^="row-"]{
display: flex;
flex-direction: row;
[class ^="box-"]{
background-color: #eae672;
font-size: 90px;
padding: 10px;
border: 2px solid black;
box-sizing: content-box;
115
Chapter 4 Media Queries
<html>
<head>
<title>Media Query Example</title>
<link rel="stylesheet" type="text/css" href="mq.css">
</head>
<body>
<div class="container">
<div class="row-1">
<div class="box-1"><img src="../../../../../
images/ace-gc9bd94751_1280.png" width="100px"
height="100px"></div>
<div class="box-2"><img src="../../../../../
images/clubs-g847a850ff_1280.png" width="100px"
height="100px"></div>
<div class="box-3"><img src="../../../../../
images/five-g98e284f73_1280.png" width="100px"
height="100px"></div>
</div>
<div class="row-2">
<div class="box-4"><img src="../../../../../
images/nine-g12e3b987e_1280.png" width="100px"
height="100px"></div>
<div class="box-5"><img src="../../../../../
images/playing-card-g1c01e2707_1280.png"
width="100px" height="100px"></div>
<div class="box-6"><img src="../../../../../
images/playing-card-g721103018_1280.png"
width="100px" height="100px"></div>
</div>
116
Chapter 4 Media Queries
<div class="row-3">
<div class="box-7"><img src="../../../../../
images/playing-card-g81e13fa7e_1280.png"
width="100px" height="100px"></div>
<div class="box-8"><img src="../../../../../
images/playing-card-gda6f55dd7_1280.png"
width="100px" height="100px"></div>
<div class="box-9"><img src="../../../../../
images/spades-gf13173e2d_1280.png"
width="100px" height="100px"></div>
</div>
</div>
</body>
</html>
118
Chapter 4 Media Queries
S
ummary
This chapter talked about media queries and how to use them. We started
with what a media query is, followed by how a media query works., we
built a simple media query project to better understand how they work.
119
CHAPTER 5
dynamic user experiences. In this chapter, we will delve into the exciting
capabilities that CSS3 offers to front-end developers and how it has
transformed the web development landscape.
122
Chapter 5 CSS Selectors, Color Modes, and More
123
Chapter 5 CSS Selectors, Color Modes, and More
124
Chapter 5 CSS Selectors, Color Modes, and More
125
Chapter 5 CSS Selectors, Color Modes, and More
126
Chapter 5 CSS Selectors, Color Modes, and More
127
Chapter 5 CSS Selectors, Color Modes, and More
128
Chapter 5 CSS Selectors, Color Modes, and More
.round-edge{
-khtml-border-radius: 10px; /* Konqueror */
-rim-border-radius: 10px; /* RIM */
-ms-border-radius: 10px; /* Microsoft */
-o-border-radius: 10px; /* Opera */
-moz-border-radius: 10px; /* Mozilla (e.g Firefox) */
-webkit-border-radius: 10px; /* Webkit (e.g. Safari and
Chrome) */
border-radius: 10px; /* W3C */
}
# Compare and add code and text from book
<div id="headlines">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing
elit. Non magni ad qui earum natus aspernatur sequi
voluptate
possimus sint praesentium! Natus, ducimus! A velit iste
cumque placeat ut adipisci et. Lorem, ipsum dolor sit
129
Chapter 5 CSS Selectors, Color Modes, and More
Visual Studio Code provides a way to generate the lorem ipsum text by
typing Lorem and pressing Enter on autosuggestion.
Let’s use the CSS code to make this text flow in a columnar fashion.
#headlines {
column-width: 15em;
}
This CSS code will arrange the text in columns no more than 15em
wide (see Figure 5-1).
130
Chapter 5 CSS Selectors, Color Modes, and More
The iPad Air will show the content as displayed in Figure 5-2.
131
Chapter 5 CSS Selectors, Color Modes, and More
#headlines {
column-width: 15em;
column-rule: thin solid steelblue;
column-gap: 2em;
}
132
Chapter 5 CSS Selectors, Color Modes, and More
Word Wrapping
In columnar design, there will times when one needs to break a long word
onto the next line because it just won’t fit in the space available. Without
word wrapping, the text will overflow from its allocated space, as shown in
Figure 5-5.
133
Chapter 5 CSS Selectors, Color Modes, and More
Check the last line of the last column. It is breaking its allocated space
and overflowing. CSS provides an easy way to fix this and works well with
older versions of browsers as well.
You need to include the following code in your CSS:
word-wrap : break-word;
* {
margin: 0;
padding: 0;
}
134
Chapter 5 CSS Selectors, Color Modes, and More
Attribute Selectors
CSS3 introduced attribute selectors to allow developers to select elements
based on their attributes and attribute values. This gives greater flexibility
in styling and targeting specific elements dynamically.
Here is an example:
input[type="text"] {
background-color: #f2f2f2;
}
Negation Selector
The negation selector (:not) enables developers to select elements that do
not match a particular selector. It is a powerful tool to override styles or
exclude specific elements from a selection.
Here is an example:
p:not(.highlight) {
color: #333;
}
h2 + p {
margin-top: 10px;
}
135
Chapter 5 CSS Selectors, Color Modes, and More
h2 ~ p {
margin-top: 10px;
}
li:first-child {
font-weight: bold;
}
li:last-child {
margin-bottom: 10px;
}
136
Chapter 5 CSS Selectors, Color Modes, and More
Empty Selector
The empty selector (:empty) selects elements that have no child elements
or text content. It can be used to style elements that do not contain any
content.
Here’s an example:
div:empty {
display: none;
}
li:nth-child(2n) {
background-color: #f2f2f2;
}
Root Selector
The root selector (:root) targets the root element of a document, usually
the <html> element. It is useful for applying styles to the entire document.
Here’s an example:
:root {
font-size: 16px;
}
137
Chapter 5 CSS Selectors, Color Modes, and More
CSS3 has revolutionized the way web developers style and select
elements on web pages. The new selectors introduced in CSS3 offer
increased flexibility and control, allowing developers to target elements
with precision. By utilizing these selectors effectively, developers can
create cleaner, more maintainable code and enhance the user experience.
Leveraging the power of these selectors is a valuable skill for any web
developer seeking to create modern and visually appealing websites.
element[attribute="value"] {
/* Styles to be applied */
}
138
Chapter 5 CSS Selectors, Color Modes, and More
Prefix Match
The prefix match selector ([attribute^=“value”]) targets elements whose
attribute value begins with a specific value.
Here’s an example:
a[href^="https://"] {
/* Styles applied to links with URLs starting with
"https://" */
}
Suffix Match
The suffix match selector ([attribute$=“value”]) targets elements whose
attribute value ends with a specific value.
Here’s an example:
img[src$=".png"] {
/* Styles applied to images with source URLs ending in
".png" */
}
139
Chapter 5 CSS Selectors, Color Modes, and More
Substring Match
The substring match selector ([attribute*=“value”]) targets elements whose
attribute value contains a specific value anywhere within it.
Here’s an example:
input[type*="email"] {
/* Styles applied to input fields with a type containing
the word "email" */
}
Word Match
The word match selector ([attribute~=“value”]) targets elements whose
attribute value contains a specific value as a whole word (separated by
spaces).
Here’s an example:
p[class~="highlight"] {
/* Styles applied to paragraphs with the class name
containing the word "highlight" */
}
Practical Examples
Let’s explore some practical examples to demonstrate the power of
substring-matching attribute selectors.
Example 1: Styling External Links
a[href^="http://"]:not([href^="https://"]) {
/* Styles applied to external links (excluding
"https://") */
/* e.g., http://example.com */
}
140
Chapter 5 CSS Selectors, Color Modes, and More
a[href$=".pdf"] {
/* Styles applied to links pointing to PDF files */
}
input[type*="password"]:invalid {
/* Styles applied to password input fields when they are
invalid */
}
div[class~="important"] {
/* Styles applied to div elements with the class name
containing the word "important" */
}
141
Chapter 5 CSS Selectors, Color Modes, and More
and convey the desired tone and mood. With the advancements in CSS3,
designers now have more power and flexibility to unleash their creativity
and create stunning custom typography on the Web. In this section, we
will delve into the world of custom web typography in CSS3, exploring the
techniques and features that allow designers to push the boundaries of
typographic design.
Web Fonts
One of the fundamental components of custom web typography is the use
of web fonts. CSS3 provides support for embedding custom fonts using
the @font-face rule. This allows designers to include unique typefaces that
aren’t commonly available on users’ systems. By incorporating custom
web fonts, designers can align their typography with the overall design
concept, creating a more cohesive and personalized user experience.
Font Stacks
Font stacks are a collection of fallback fonts specified in CSS. These stacks
ensure that if a particular font is not available, the browser automatically
selects the next available font from the stack. With CSS3, designers can
create font stacks that include custom web fonts, system fonts, and even
fallbacks from popular font families. This ensures consistent typography
across different devices and platforms while still preserving the intended
visual aesthetic.
142
Chapter 5 CSS Selectors, Color Modes, and More
strokes, and unique decorations to the text, making it stand out and
capturing users’ attention. Customizing these properties creatively can
help emphasize important elements, highlight headings, or create visual
hierarchy within the content.
Variable Fonts
CSS3 brings the exciting concept of variable fonts, which are font files
that contain multiple variations within a single file. These variations can
include different weights, styles, and even width adjustments. By utilizing
variable fonts, designers can achieve greater flexibility in customizing
typography, allowing for smooth transitions between font styles and
seamless responsiveness across different screen sizes. This enables the
creation of unique typographic designs that adapt to the needs of the
content and the device it is displayed on.
143
Chapter 5 CSS Selectors, Color Modes, and More
@font-face Typography
in Responsive Design
In today’s digital landscape, responsive design has become crucial to
ensure a seamless user experience across devices of various sizes and
resolutions. Typography plays a vital role in web design, and with the @
font-face rule in CSS, designers can now incorporate custom fonts to
enhance the visual appeal of their websites. In this section, we will explore
how @font-face typography can be effectively utilized in responsive
design, along with practical examples.
Font Selection
When considering the @font-face typography for responsive design, it
is essential to choose fonts that are legible and visually appealing across
different screen sizes. Opt for fonts that offer a variety of weights and
styles to allow flexibility in adjusting the typography for different contexts.
For example, a font like Open Sans provides various weights, allowing
designers to adapt the font to different device resolutions seamlessly.
Here’s an example:
@font-face {
font-family: 'Open Sans';
src: url('open-sans-regular.woff2') format('woff2'),
url('open-sans-regular.woff') format('woff');
font-weight: normal;
font-style: normal;
}
144
Chapter 5 CSS Selectors, Color Modes, and More
Font Formats
To ensure compatibility across different browsers and devices, include
font files in multiple formats, such as TrueType (.ttf ), OpenType (.otf ),
Web Open Font Format (.woff ), and Web Open Font Format 2.0 (.woff2).
This allows the browser to select the appropriate format based on its
capabilities, ensuring that the custom font is displayed correctly.
Here’s an example:
@font-face {
font-family: 'Open Sans';
src: url('open-sans-regular.woff2') format('woff2'),
url('open-sans-regular.woff') format('woff'),
url('open-sans-regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Media Queries
Media queries are essential for adapting typography to different screen
sizes and devices in responsive design. By using media queries, designers
can adjust font sizes, line heights, and other typographic properties based
on the viewport dimensions.
Here’s an example:
145
Chapter 5 CSS Selectors, Color Modes, and More
Fluid Typography
Fluid typography ensures that font sizes and other typographic properties
scale smoothly with the viewport size. This technique maintains optimal
readability and aesthetics across different devices.
Here’s an example:
Performance Optimization
To optimize font loading and page performance, designers can implement
techniques such as font subsetting, font preloading, and asynchronous
font loading. These techniques help reduce page load times, particularly
on mobile devices with limited bandwidth.
Here’s an example:
146
Chapter 5 CSS Selectors, Color Modes, and More
/* HSLA */
147
Chapter 5 CSS Selectors, Color Modes, and More
148
Chapter 5 CSS Selectors, Color Modes, and More
Transparent
CSS3 introduced the transparent keyword, which allows designers to
create fully transparent elements. This is particularly useful when creating
layered effects or overlays.
Here is a code example:
Most of the IDEs provide their own color picker with RGB and hex
values. Figure 5-7 shows the Visual Studio Code editor, which shows only
RGB values on the top heading.
149
Chapter 5 CSS Selectors, Color Modes, and More
Summary
This chapter focused on the CSS selectors, color modes, and different ways
the same color can be defined and interpreted by Cascading Style Sheets.
The chapter started by exploring the power of CSS3 and understanding
the building blocks of CSS3 such as selectors, properties, values, and
declarations. It also covered the specific browser vendors’ related prefixes,
how multiple columns can be created, and how to resolve the flow of the
longer words in columns. The chapter explained the new CSS selectors
and how CSS3 string manipulation works. We then covered custom web
typography followed by the @font-face typography. The last topic for this
chapter was CSS color formats.
150
CHAPTER 6
Animations and
Transitions in CSS3
Animation is a new and promising feature in CSS and used to
communicate or promote various visual aids. This chapter focuses on how
to create animations using CSS3. It covers animating text content, along
with the properties you need and how the browser will display it. It then
covers animating objects. Next the chapter covers CSS transitions and the
attributes required to create those transitions. The last two topics are 2D
and 3D transformations.
@keyframes slide-in {
from { opacity: 0; transform: translateX(-100px); }
to { opacity: 1; transform: translateX(0); }
}
Using the defined keyframe in the animation property looks like this:
.element {
animation-name: slide-in;
animation-duration: 1s;
animation-timing-function: ease-in-out;
animation-delay: 1s;
animation-iteration-count: infinite;
animation-fill-mode: forwards;
color: #d42e2e;
align-self: center;
}
Figure 6-1 shows how the browser will display the text or image
animated a movement from left to right.
152
Chapter 6 Animations and Transitions in CSS3
Animating an Object
Let’s look at another code example where an object is moving from left to
right and from the bottom up and then comes back to its original position.
At the same time it is changing colors.
153
Chapter 6 Animations and Transitions in CSS3
div {
width: 150px;
height: 150px;
position: relative;
background: teal;
-webkit-animation: second 7s; /* Chrome, Safari, Opera */
animation: second 7s;
}
/* Standard syntax */
@keyframes second {
0% {background:teal; left:0px; top:0px;}
25% {background:turquoise; left:300px; top:0px;}
50% {background:seagreen; left:300px; top:200px;}
75% {background:saddlebrown; left:0px; top:200px;}
100% {background:teal; left:0px; top:0px;}
}
Now all that is required is to place a <div> tag in the HTML file and load
it into any modern browser. It should display something like Figure 6-2.
154
Chapter 6 Animations and Transitions in CSS3
CSS3 Transitions
Web design is all about creating captivating user experiences, and CSS3
transitions offer a powerful tool for adding smooth and elegant animations
to your web pages. With CSS3 transitions, developers can easily animate
changes in CSS property values, such as color, size, position, and opacity,
creating visually appealing and interactive elements. In this section, we
will explore the versatility of CSS3 transitions and their key concepts and
provide a comprehensive guide on how to implement them effectively in
your web designs.
155
Chapter 6 Animations and Transitions in CSS3
button {
transition: background-color 0.3s ease-in-out;
}
156
Chapter 6 Animations and Transitions in CSS3
button:hover {
background-color: #ff0000;
}
157
Chapter 6 Animations and Transitions in CSS3
The browser will display the HTML page when the mouse hovers over
the button (see Figure 6-4).
transition-property
The transition-property property specifies the CSS properties you want to
animate. You can specify multiple properties separated by commas or use
the value all to animate all the applicable properties. For example:
.element {
transition-property: width, opacity;
}
158
Chapter 6 Animations and Transitions in CSS3
transition-duration
The transition-duration property sets the duration over which the transition
occurs. It determines how long it takes for the transition to complete, and it
accepts time values in seconds (s) or milliseconds (ms). For example:
.element {
transition-duration: 0.5s;
}
This specifies that the transition should take half a second to complete.
transition-timing-function
The transition-timing-function property controls the pace of the transition.
It determines how the intermediate property values are calculated over time.
CSS3 provides several predefined timing functions, including the following:
You can also use the cubic-bezier() function to create custom timing
functions. For example:
.element {
transition-timing-function: ease-in-out;
}
159
Chapter 6 Animations and Transitions in CSS3
transition-delay
The transition-delay property introduces a delay before the transition
starts. It allows you to control when the transition should begin after a
state change. You can specify the delay using time values in seconds (s) or
milliseconds (ms). For example:
.element {
transition-delay: 0.2s;
}
transition
The transition shorthand property allows you to specify the transition
property, duration, timing function, and delay in a single line. The values
are specified in the following order: transition-property, transition-
duration, transition-timing-function, and transition-delay. Here’s an
example:
160
Chapter 6 Animations and Transitions in CSS3
.element {
transition: width 0.5s ease-in-out 0.2s;
}
transition-property
The transition-property shorthand property allows you to specify multiple
properties to be transitioned. You can separate the property names using
commas. For example:
.element {
transition-property: width, height, opacity;
}
transition-duration
The transition-duration shorthand property allows you to specify the
duration for multiple transitions. You can provide multiple time values
separated by commas. For example:
.element {
transition-duration: 0.5s, 1s, 0.3s;
}
161
Chapter 6 Animations and Transitions in CSS3
transition-timing-function
The transition-timing-function shorthand property allows you to specify
the timing functions for multiple transitions. You can provide multiple
timing function values separated by commas. For example:
.element {
transition-timing-function: ease-in-out, linear, ease-in;
}
transition-delay
The transition-delay shorthand property allows you to specify the delay
for multiple transitions. You can provide multiple time values separated by
commas. For example:
.element {
transition-delay: 0.2s, 0.5s, 0s;
}
In this example, each transition will have a different delay: 0.2 seconds,
0.5 seconds, and no delay (0 seconds).
By using these shorthand properties, you can easily and efficiently
define multiple transition-related values, making your CSS code more
concise and readable. Remember to experiment with different values to
achieve the desired effects for your transitions.
162
Chapter 6 Animations and Transitions in CSS3
linear
The linear timing function produces a constant transition speed
throughout the animation. It creates a linear progression without any
acceleration or deceleration. This function is suitable for animations
requiring a consistent speed. For example:
transition-timing-function: linear;
163
Chapter 6 Animations and Transitions in CSS3
ease
The ease timing function is the default in CSS3 transitions. It starts slowly,
accelerates in the middle, and slows down toward the end. The ease
function adds a subtle easing effect, providing a more natural and pleasing
animation. For example:
transition-timing-function: ease;
ease-in
The ease-in timing function starts slowly and accelerates toward the end.
It produces a smooth and gentle entrance, perfect for transitions that
emphasize the beginning. For example:
transition-timing-function: ease-in;
ease-out
The ease-out timing function starts quickly and decelerates toward the
end. It creates a smooth and gradual exit, often used to highlight the end of
a transition. For example:
transition-timing-function: ease-out;
ease-in-out
The ease-in-out timing function combines the characteristics of ease-in
and ease-out. It starts slowly, accelerates in the middle, and decelerates
toward the end. This timing function provides a balanced effect suitable
for a wide range of transitions. For example:
transition-timing-function: ease-in-out;
164
Chapter 6 Animations and Transitions in CSS3
CSS3 2D Transitions
CSS3 offers a wide range of powerful tools to bring creativity and
interactivity to web design. Among these tools, 2D transformations provide
the ability to manipulate elements in two-dimensional space, allowing for
165
Chapter 6 Animations and Transitions in CSS3
Translation
Translation allows elements to be moved or shifted along the horizontal
and vertical axes. This can be achieved using the translate() function,
specifying the distance to move in each direction. For example:
.element {
transform: translate(50px, 20px);
}
This will move the element 50 pixels to the right and 20 pixels down.
Scaling
Scaling allows elements to be resized larger or smaller. The scale() function
can be used to define the scaling factors for the width and height of an
element. For example:
166
Chapter 6 Animations and Transitions in CSS3
.element {
transform: scale(1.2);
}
Rotation
Rotation enables elements to be rotated around a specified point. The
rotate() function defines the angle of rotation in degrees. For example:
.element {
transform: rotate(45deg);
}
Skewing
Skewing allows elements to be distorted along the horizontal or vertical
axis. The skew() function sets the angles of skew in degrees. For example:
.element {
transform: skew(10deg, -5deg);
}
167
Chapter 6 Animations and Transitions in CSS3
Origin Manipulation
The transformation origin specifies the point around which
transformations are applied. By default, the origin is set to the center of
the element. However, it can be customized using the transform-origin
property. For example:
.element {
transform-origin: top left;
}
This will set the transformation origin to the top-left corner of the
element.
Combining Transformations
Multiple transformations can be combined to achieve complex effects.
Each transformation is applied in the order they are specified. For
example:
.element {
transform: translate(50px, 50px) rotate(45deg) scale(1.2);
}
This will first translate the element, then rotate it, and finally scale it.
CSS3 2D transformations provide a powerful toolkit for creating
visually engaging web experiences. By leveraging translation, scaling,
rotation, skewing, and origin manipulation, developers can transform
elements, adding depth, motion, and interactivity to their designs.
Whether it’s animating a navigation menu, creating a playful hover effect,
or adding a unique perspective to images, CSS3 2D transformations allow
for limitless creativity and innovation. So, embrace the power of CSS3 2D
transformations, experiment, and let your web designs come to life with
captivating transformations.
168
Chapter 6 Animations and Transitions in CSS3
CSS3 3D Transformations
In the realm of modern web design, creating visually captivating and
interactive experiences is a top priority. CSS3 offers a powerful set of tools
to bring designs to life, and one such tool is CSS3 3D transformations.
With CSS3 3D transformations, developers can manipulate elements in
three-dimensional space, allowing for stunning and immersive effects.
In this section, we will explore the world of CSS3 3D transformations,
understanding their concepts and discovering how they can take web
design to the next level.
Perspective
Perspective is a critical concept in CSS3 3D transformations. It establishes
the depth and viewing perspective for the 3D space. By applying the
perspective property to a parent element, you define the distance at which
the viewer perceives the 3D space. This property creates a sense of depth
and realism.
169
Chapter 6 Animations and Transitions in CSS3
Transformations in 3D Space
CSS3 3D transformations provide a range of properties to manipulate
elements in three-dimensional space.
Combining Transformations
Developers can combine multiple transformations to achieve complex 3D
effects. By applying different rotation, scaling, translation, and skewing
properties, elements can be transformed in unique and captivating ways.
Experimentation and fine-tuning are key to achieving desired results.
170
Chapter 6 Animations and Transitions in CSS3
.container {
perspective: 800px;
}
Defining 3D Transformations
Apply 3D transformations to the target elements using the appropriate
transformation properties. These transformations manipulate elements in
three-dimensional space. For example:
.element {
transform: rotateY(45deg) translateZ(100px);
}
171
Chapter 6 Animations and Transitions in CSS3
Summary
This chapter covered animations, animation properties, and transitions
and showed how to implement a simple CSS transition. This chapter
also covered the transition shorthand property along with the timing
functions. The chapter explained how to create a custom timing function
with a code example. Following this, the chapter explained CSS 2D and 3D
transformations.
172
CHAPTER 7
Background
and Shadows in CSS
This chapter covers the shadow effect using CSS. The first topic covered is
text shadows. We’ll talk about how to add shadows to text to make it more
attractive, what color and how color palletes can be applied, and what the
properties of the shadows are. It also explains how to prevent text shadows
using CSS. Another amazing feature that will be covered is the embossed
text shadow effect. We’ll also cover box shadows, background gradients,
and more.
.text {
text-shadow: 2px 2px 2px #ff0000;
}
Let’s try to understand what this syntax means. As per the rule values,
the shorthand rules go right and then down. Hence, the first 2px value
represents the shadow to the right, followed by the 2px value representing
the shadow down, and the next 2px value represents the blur. Lastly, the
color of the shadow is specified (it can be in hex, HSL, or RGB).
Let’s consider the following code example to see how text-
shadow works.
Here is the HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Text Shadow Using CSS3</title>
<style>
.shadow-text {
font-size: 36px;
font-weight: bold;
text-shadow: 2px 2px 4px #e32a2a;
}
</style>
</head>
<body>
<h1 class="shadow-text">Hello, World!</h1>
</body>
</html>
174
Chapter 7 Background and Shadows in CSS
As observed, the value for the shadow’s horizontal and vertical display
goes to the right and down. What if you need to shadow the text to the
left and up? It is a simple process. Provide a negative value to the first two
attributes, as shown in the following code:
<!DOCTYPE html>
<html>
<head>
<title>Text Shadow Using CSS3</title>
<style>
.shadow-text {
font-size: 36px;
font-weight: bold;
text-shadow: -2px -2px 4px rgb(227, 42, 42);
}
</style>
</head>
<body>
<h1 class="shadow-text">Hello, World!</h1>
</body>
</html>
175
Chapter 7 Background and Shadows in CSS
<!DOCTYPE html>
<html>
<head>
<title>Text Shadow Using CSS3</title>
<style>
.shadow-text {
font-size: 36px;
font-weight: bold;
text-shadow: none;
}
</style>
</head>
<body>
<h1 class="shadow-text">Hello, World!</h1>
</body>
</html>
176
Chapter 7 Background and Shadows in CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Embossed Text Shadow</title>
<style>
.embossed-text {
font-size: 48px;
text-align: center;
color: #dad4d4; /* Set the text color */
text-shadow: 1px 1px 0 #262525, -1px -1px 0 #666;
/*
The text-shadow property takes a comma-separated list
of shadows.
177
Chapter 7 Background and Shadows in CSS
178
Chapter 7 Background and Shadows in CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
179
Chapter 7 Background and Shadows in CSS
background-color: #333;
padding: 20px;
}
</style>
</head>
<body>
<div class="shadow-text">Multiple Text Shadows</div>
</body>
</html>
180
Chapter 7 Background and Shadows in CSS
You can add as many shadows as you want, and you’re not limited
to just using different colors. You can experiment with various offsets,
blur radii, and colors to create unique and visually appealing effects for
your text.
Figure 7-4 shows what this looks like in a browser.
Box Shadows
CSS3 brought a plethora of new possibilities for web designers and
developers to create eye-catching and dynamic user interfaces. One of the
most versatile and powerful features introduced in CSS3 is the box-shadow
property. With box-shadow, designers can add depth, dimension, and
visual interest to elements on their web pages, creating a more engaging
user experience. In this section, we will explore the box-shadow property
in CSS3 and learn how to wield it effectively to enhance your designs.
181
Chapter 7 Background and Shadows in CSS
182
Chapter 7 Background and Shadows in CSS
183
Chapter 7 Background and Shadows in CSS
184
Chapter 7 Background and Shadows in CSS
185
Chapter 7 Background and Shadows in CSS
Background Gradients
In CSS3, you can create background gradients using the background-
image property with the linear-gradient() or radial-gradient() functions.
Gradients allow you to smoothly blend multiple colors together, creating
visually appealing and dynamic backgrounds for your web elements. Let’s
explore how to use these functions to create linear and radial gradients.
• Linear gradient
186
Chapter 7 Background and Shadows in CSS
• Radial gradient
187
Chapter 7 Background and Shadows in CSS
188
Chapter 7 Background and Shadows in CSS
width: 200px;
height: 200px;
background-image: radial-gradient(circle at 60%
40%, #f00 10%, #0f0 70%);
}
189
Chapter 7 Background and Shadows in CSS
With CSS3 background gradients, you can unleash your creativity and
design stunning backgrounds for your web elements. Experiment with
different colors, directions, shapes, and color stops to achieve the desired
effects and enhance the overall aesthetics of your web design. Gradients
are a powerful tool that can help you create visually engaging and modern
interfaces that captivate your users.
Repeating Gradients
In CSS3, you can create repeating gradients using the repeating-linear-
gradient() and repeating-radial-gradient() functions. Repeating gradients
allow you to create a seamless pattern by repeating the gradient at regular
intervals. This can be particularly useful for creating backgrounds and
textures. Let’s explore how to use these functions to create repeating
gradients.
190
Chapter 7 Background and Shadows in CSS
191
Chapter 7 Background and Shadows in CSS
192
Chapter 7 Background and Shadows in CSS
sizes, you can achieve unique and eye-catching designs that add depth
and interest to your web pages. So, go ahead and unleash your creativity
with repeating gradients to enhance the aesthetics of your web design!
193
Chapter 7 Background and Shadows in CSS
194
Chapter 7 Background and Shadows in CSS
195
Chapter 7 Background and Shadows in CSS
196
Chapter 7 Background and Shadows in CSS
197
Chapter 7 Background and Shadows in CSS
198
Chapter 7 Background and Shadows in CSS
Summary
This chapter covered various techniques to add shadow effects. The first
and simplest way is to add shadows to text. Knowing what color values are
allowed is important as is knowing how to prevent text shadows. Adding an
embossed effect to text shadow the right way enhances the UX experience.
It is not restricted to only one shadow effect; multiple effects can be added.
The chapter also covered box shadows and background gradients, both
linear and radial. We also covered icons and best practices.
199
CHAPTER 8
HTML5 Forms
HTML5, the latest version of the Hypertext Markup Language, introduced
significant improvements to web forms, revolutionizing the way we collect
user data and enhancing the overall user experience. In this section, we
will delve into the world of HTML5 forms, exploring their new features,
benefits, and best practices for creating powerful and user-friendly
web forms.
202
Chapter 8 Forms with HTML
• Accessibility considerations
203
Chapter 8 Forms with HTML
HTML5 forms have transformed the way we collect user data on the
Web. With new semantic elements, input types, attributes, and built-in
validation, web developers can create powerful and user-friendly forms
that improve data accuracy and enhance the overall user experience. By
leveraging the capabilities of HTML5 forms and considering accessibility
and responsiveness, web designers can ensure that their forms are
efficient, accessible, and appealing to users across all devices and
platforms. Embracing HTML5 forms is an essential step toward creating
modern, dynamic, and user-centric web applications.
Figure 8-1 shows a simple user registration form without any CSS.
204
Chapter 8 Forms with HTML
The form elements have three sections: a fieldset, a legend, and each
input element wrapped around a <div> (which can be observed in the
following code):
<fieldset>
<legend>Personal Information:</legend>
<div>
<label for="name">Name:</label>
<input type="text" id="u_name" name="u_
name" required aria-required="true"
placeholder="John Doe">
</div>
<div>
<label for="email">Email Address:</label>
<input type="text" id="u_email" name="u_email"
required aria-required="true" placeholder="John.
[email protected]">
</div>
<div>
<label for="phone">Phone Number:</label>
<input type="text" id="u_phone" name="u_
phone" required aria-required="true"
placeholder="987-654-321">
</div>
<div>
205
Chapter 8 Forms with HTML
Input Type
The input type denotes the type of input and various validations along with
whether the field is mandatory or not. Examples of input types are text
box, text area, checkbox, drop-downs, radio buttons, etc. The input type
element most commonly has id and name attributes, and its validation
can be controlled by JavaScript or mentioning specific tags like required
or aria-required. It also can have a placeholder value that can be used to
direct a user to indicate what values the input field will be accepting.
required
A Boolean value is used to indicate if the input field is mandatory for the
user to provide a value. The following values can be used to do so:
required aria-required=”true”
206
Chapter 8 Forms with HTML
placeholder
This is how placeholder code can be written:
placeholder=”e.g. 987-654-3210”
The placeholder value is displayed by default in the field where this
is defined. The previous example denotes a phone number and will be
displayed by default. The user can click the input field and provide the
phone number, and the field value will now contain the user-provided
input. If this field is in focus and the user has yet to enter the value, the
placeholder value disappears, and it will magically come back if the focus
is moved from this particular input field and the user has not entered any
value for it.
autofocus
The autofocus attribute is a Boolean attribute that can be applied to certain
form elements to automatically set the focus on them when the page
loads. When an element has the autofocus attribute, it becomes the active
element on the page, which means the user can start interacting with it
immediately without needing to manually click or tap the field.
The autofocus attribute can be used with a variety of form elements,
such as text inputs, text areas, checkboxes, radio buttons, and buttons.
However, it’s essential to use it judiciously to avoid overwhelming users
with unnecessary focus changes, which could disrupt their browsing
experience.
207
Chapter 8 Forms with HTML
Points to Consider
Consider the following points:
208
Chapter 8 Forms with HTML
autocomplete
The autocomplete attribute is used to control whether a web browser should
remember the autofill form field values based on the user’s previous input.
The attribute is applied to individual form fields to specify whether the
browser should provide suggestions for that particular field. The autocomplete
attribute can be set to different values to control the autofill behavior.
The autocomplete attribute can be applied to various types of form
fields, such as text inputs, passwords, email addresses, and more. It is
particularly useful for login forms, registration forms, and other types of
forms where users often enter the same information repeatedly.
209
Chapter 8 Forms with HTML
• autocomplete=“current-password”: Suggests
previously entered passwords that are used for the
current site or application
• autocomplete=“address-line1” and
autocomplete=“address-line2”: Suggests parts of
the user’s address for forms that collect address
information
• autocomplete=“credit-card-number”: Suggests
previously entered credit card numbers
• autocomplete=“credit-card-expiry”: Suggests
previously entered credit card expiry dates
• autocomplete=“credit-card-cvc”: Suggests
previously entered credit card verification codes
210
Chapter 8 Forms with HTML
211
Chapter 8 Forms with HTML
<!DOCTYPE html>
<html>
<head>
<title>Datalist Example</title>
</head>
<body>
<label for="programmingLanguage">Select a programming
language:</label>
<input type="text" id="programmingLanguage" list="languages">
<datalist id="languages">
<option value="JavaScript">
<option value="Python">
<option value="Java">
<option value="C++">
<option value="Ruby">
</datalist>
</body>
</html>
212
Chapter 8 Forms with HTML
<!DOCTYPE html>
<html>
<head>
<title>Datalist Example</title>
</head>
<body>
<label for="programmingLanguage">Select a programming
language:</label>
<input type="text" id="programmingLanguage" list="languages">
<datalist id="languages">
<option value="JavaScript">
<option value="Python">
<option value="Java">
<option value="C++">
<option value="Ruby">
</datalist>
</body>
</html>
213
Chapter 8 Forms with HTML
Note
• The <datalist> element is not visible on the page.
It acts as a behind-the-scenes data source for the
associated input field.
• The options defined in the <datalist> are suggestions,
but the user can still type a custom value in the input
field if they don’t want to choose from the predefined
options.
214
Chapter 8 Forms with HTML
215
Chapter 8 Forms with HTML
216
Chapter 8 Forms with HTML
Text Input
The input element with type=“text” is used to create a single-line text input
field in web forms. This input type is one of the most commonly used and
allows users to enter plain text, such as names, email addresses, messages,
or any other free-form textual information.
217
Chapter 8 Forms with HTML
218
Chapter 8 Forms with HTML
Password Input
The input element with type=“password” is used to create a password
input field in web forms. This input type is specifically designed for
entering sensitive information, such as passwords or other confidential
data, and it masks the characters entered by the user to protect their
privacy.
Here’s the basic syntax of the password input:
219
Chapter 8 Forms with HTML
Number Input
The input element with type=“number” is used to create a numeric input
field in web forms. This input type is specifically designed for accepting
numeric values, such as integers or floating-point numbers. The number
input provides additional controls such as arrows to increase or decrease
the numeric value, making it easier for users to input numeric data.
Here’s the basic syntax of the number input:
220
Chapter 8 Forms with HTML
• min: The min attribute sets the minimum value that the
input field can accept. Users cannot enter a value lower
than the specified minimum.
Email Input
The input element with type=“email” is used to create an email input field
in web forms. This input type is specifically designed for collecting email
addresses from users and provides built-in email validation to ensure that
the entered value is in a valid email format.
221
Chapter 8 Forms with HTML
222
Chapter 8 Forms with HTML
URL Input
The input element with type=“url” is used to create a URL input field
in web forms. This input type is specifically designed for collecting web
addresses (URLs) from users and provides built-in URL validation to
ensure that the entered value is in a valid URL format.
Here’s the basic syntax of the URL input:
223
Chapter 8 Forms with HTML
Tel Input
The input element with type=“tel” is used to create a telephone number
input field in web forms. This input type is specifically designed for
collecting telephone numbers from users and provides features that are
beneficial for mobile devices, such as displaying a numeric keypad when
focused.
Here’s the basic syntax of the telephone number input:
224
Chapter 8 Forms with HTML
Date Input
The input element with type=“date” is used to create a date input field in
web forms. This input type is specifically designed for collecting dates from
users and provides a date picker or calendar widget, making it easier for
users to select a date.
Here’s the basic syntax of the date input:
• min: The min attribute sets the minimum date that the
input field can accept. Users cannot select a date earlier
than the specified minimum.
225
Chapter 8 Forms with HTML
• max: The max attribute sets the maximum date that the
input field can accept. Users cannot select a date later
than the specified maximum.
Time Input
The input element with type=“time” is used to create a time input field
in web forms. This input type is specifically designed for collecting time
values from users and provides a time picker, making it easier for users to
select a specific time.
Here’s the basic syntax of the time input:
226
Chapter 8 Forms with HTML
• max: The max attribute sets the maximum time that the
input field can accept. Users cannot select a time later
than the specified maximum.
Datetime Input
The input element with type=“datetime-local” is used to create a datetime
input field in web forms. This input type is specifically designed for
collecting date and time values from users, allowing them to choose both
the date and time using a date and time picker.
227
Chapter 8 Forms with HTML
228
Chapter 8 Forms with HTML
Month Input
The input element with type=“month” is used to create a month input field
in web forms. This input type is specifically designed for collecting month
and year values from users, allowing them to choose a specific month and
year using a month picker.
Here’s the basic syntax of the month input:
229
Chapter 8 Forms with HTML
Week Input
The input element with type=“week” is used to create a week input
field in web forms. This input type is specifically designed for collecting
week values from users, allowing them to choose a specific week using a
week picker.
Here’s the basic syntax of the week input:
230
Chapter 8 Forms with HTML
Color Input
The input element with type=“color” is used to create a color input
field in web forms. This input type is specifically designed for collecting
color values from users, allowing them to choose a specific color using a
color picker.
231
Chapter 8 Forms with HTML
Checkbox Input
The input element with type=“checkbox” is used to create a checkbox
input field in web forms. This input type allows users to select one or
multiple options from a set of choices.
Here’s the basic syntax of the checkbox input:
232
Chapter 8 Forms with HTML
Radio Input
The input element with type=“radio” is used to create a radio button input
field in web forms. Radio buttons allow users to select one option from a
group of mutually exclusive choices.
Here’s the basic syntax of the radio input:
233
Chapter 8 Forms with HTML
File Input
The input element with type=“file” is used to create a file input field in web
forms. This input type allows users to browse their local file system and
select one or multiple files to be uploaded to a server or processed by a
client-side script.
234
Chapter 8 Forms with HTML
235
Chapter 8 Forms with HTML
Search Input
The input element with type=“search” is used to create a search input field
in web forms. This input type is specifically designed for capturing search
queries from users, and it typically provides a specialized appearance with
a search icon or magnifying glass.
Here’s the basic syntax of the search input:
236
Chapter 8 Forms with HTML
Range Input
The input element with type=“range” is used to create a range input slider
in web forms. This input type allows users to select a value from a specified
range by dragging a slider handle along a track.
Here’s the basic syntax of the range input:
237
Chapter 8 Forms with HTML
Submit Input
The input element with type=“submit” is used to create a submit button in
web forms. The submit button is used to trigger the submission of a form
to a server for processing or to initiate some other action associated with
the form.
Here’s the basic syntax of the submit input:
238
Chapter 8 Forms with HTML
Reset Input
The input element with type=“reset” is used to create a reset button in web
forms. The reset button is used to clear the user’s input and restore the
form’s fields to their default values defined in the HTML markup.
Here’s the basic syntax of the reset input:
Button Input
The input element with type=“button” is used to create a generic button
in web pages. Unlike the submit and reset buttons, the button input type
does not have any inherent default behavior related to form submissions.
Instead, it is primarily used to trigger custom JavaScript functions or
perform other non-form-related actions.
Here’s the basic syntax of the button input:
239
Chapter 8 Forms with HTML
240
Chapter 8 Forms with HTML
<!DOCTYPE html>
<html>
<head>
<!-- Add the polyfill library -->
<script src="path/to/polyfill-library.js"></script>
<!-- Other head elements go here -->
</head>
<body>
<!-- Your content here -->
</body>
</html>
241
Chapter 8 Forms with HTML
Keep in mind that not all HTML5 features can be perfectly polyfilled,
and the performance and behavior may not be identical to native support.
It’s essential to choose reputable and well-maintained polyfill libraries and
regularly update them to address any bugs or security issues. Additionally,
as browsers evolve and gain more native support, you might eventually
phase out some polyfills in favor of native support.
Summary
This chapter explained HTML form elements, how to create a form
using HTML tags, and how to validate these fields. It covered the new
form elements along with the existing ones as well as accessibility
considerations and how these forms work on mobile devices. Additionally,
the chapter covered how the newer form elements work with older
browser versions and whether one should choose to provide this support
or opt out of it.
242
CHAPTER 9
Cross-Browser
Challenges and How
to Resolve Them
This chapter covers cross-browser challenges and approaches for solving
them. We’ll cover progressive enhancement versus graceful degradation
and help you choose the best approach for the situation. The chapter also
covers Modernizr and how to use it in responsive design. Finally, we cover
media query capabilities for Internet Explorer 6, 7, and 8.
Cross-Browser Challenges
In the ever-evolving landscape of web design, crafting seamless user
experiences across a multitude of devices and screen sizes has become
paramount. Responsive design strategies play a pivotal role in achieving
this goal, ensuring that websites adapt gracefully to various contexts.
Two prominent approaches in this realm are progressive enhancement
and graceful degradation. Although these terms might sound similar,
they embody distinct philosophies, each with its own set of principles
and implications. This section delves into the fundamental differences
between progressive enhancement and graceful degradation, shedding
light on their significance in the realm of responsive design.
244
Chapter 9 Cross-Browser Challenges and How to Resolve Them
245
Chapter 9 Cross-Browser Challenges and How to Resolve Them
246
Chapter 9 Cross-Browser Challenges and How to Resolve Them
247
Chapter 9 Cross-Browser Challenges and How to Resolve Them
248
Chapter 9 Cross-Browser Challenges and How to Resolve Them
249
Chapter 9 Cross-Browser Challenges and How to Resolve Them
250
Chapter 9 Cross-Browser Challenges and How to Resolve Them
What Is Modernizr?
Modernizr is an open-source JavaScript library that simplifies the process
of detecting the availability of specific web technologies in a user’s
browser. These technologies often include HTML5 and CSS3 features
that have varying levels of support across different browsers. By checking
for the presence of these features, developers can determine whether
certain design or functionality elements are supported, allowing them to
provide graceful fallbacks or alternative solutions for older or less capable
browsers.
hy Is Modernizr Important
W
for Responsive Design?
Responsive design aims to create websites that adapt seamlessly to various
screen sizes, from large desktop monitors to mobile phones. To achieve
this, developers often rely on CSS media queries to apply different styles
based on screen dimensions. However, the effectiveness of these media
queries relies on the browser’s understanding of certain CSS3 properties.
For example, if a developer is using a CSS3 property like border-
radius to create rounded corners on elements, they need to ensure that
this property is supported by the user’s browser. If it’s not supported, the
design might break or appear differently than intended. This is where
Modernizr steps in. By detecting whether the browser supports border-
radius, developers can apply alternative styling using traditional methods
if necessary, ensuring a consistent user experience across devices.
251
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Modernizr Example</title>
<script src="modernizr.js"></script>
</head>
<body>
<div id="content">
<!-- Content goes here -->
</div>
<script>
if (Modernizr.mq('only all')) {
// Apply responsive styles here
} else {
// Provide fallback styles for older browsers
}
</script>
</body>
</html>
252
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Modernizr Example</title>
<script src="modernizr.js"></script>
<style>
.box {
width: 100px;
height: 100px;
background-color: #3498db;
transition: background-color 0.3s;
}
.box:hover {
background-color: #e74c3c;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
if (Modernizr.csstransitions) {
// Browser supports CSS transitions, enable
animations
} else {
253
Chapter 9 Cross-Browser Challenges and How to Resolve Them
254
Chapter 9 Cross-Browser Challenges and How to Resolve Them
255
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Modernizr Video Example</title>
<script src="modernizr.js"></script>
</head>
<body>
<div id="video-container">
<video controls>
<source src="example.mp4" type="video/mp4">
<p>Your browser does not support the video
tag.</p>
</video>
</div>
<script>
if (Modernizr.video) {
// Browser supports HTML5 video
} else {
// Provide alternative content or instructions
}
</script>
</body>
</html>
256
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Modernizr Canvas Example</title>
<script src="modernizr.js"></script>
</head>
<body>
<div id="canvas-container">
<canvas id="myCanvas"></canvas>
</div>
<script>
if (Modernizr.canvas) {
var canvas = document.getElementById("myCanvas");
// Start drawing on the canvas
} else {
// Provide alternative content or instructions
}
</script>
</body>
</html>
257
Chapter 9 Cross-Browser Challenges and How to Resolve Them
258
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Modernizr Min/Max Media Example</title>
<script src="modernizr.js"></script>
<style>
.container {
width: 100%;
background-color: #f2f2f2;
}
.box {
width: 50%;
height: 200px;
background-color: #3498db;
margin: 0 auto;
}
259
Chapter 9 Cross-Browser Challenges and How to Resolve Them
260
Chapter 9 Cross-Browser Challenges and How to Resolve Them
to users with older browsers that lack support for modern features. This
technique is especially relevant when dealing with browsers such as
Internet Explorer 6, 7, and 8, which have limited support for newer web
technologies.
261
Chapter 9 Cross-Browser Challenges and How to Resolve Them
<!DOCTYPE html>
<html>
<head>
<title>Conditional Loading with Modernizr</title>
<script src="modernizr.js"></script>
<link rel="stylesheet" href="styles.css">
<script>
if (!Modernizr.cssgrid) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'fallback-styles.css';
document.head.appendChild(link);
}
</script>
</head>
<body>
<!-- Your website content here -->
</body>
</html>
262
Chapter 9 Cross-Browser Challenges and How to Resolve Them
Summary
This chapter discussed the challenges faced with responsive design to
make it work across various range of browsers. We looked at progressive
enhancement versus graceful degradation. The chapter also covered
Modernizr and how it is used in responsive design. Adding media query
support for older Internet Explorer version was covered as part of this
chapter along with conditional loading with Modernizr.
263
Index
A complex effects, 183, 184
components, 182
Adjacent sibling selector, 135, 136
creating text shadows, 185
Animation
sunken elements, 184
Adobe Flash, 24, 151
working, 183
keyframe, 152
Browser prefixes, 126
object, 153, 154
Browser sniffing, 8
properties, 152
2D transformations
combining
transformations, 168
C
origin, 168 Cascading Style Sheets (CSS), 3
rotation, 167 CSS3 layouts, 61
scaling, 166 flexbox, 62
skewing, 167 floats, 63
translation, 166 grid, 62
3D transformations, 169–171 definition, 15, 18, 61
Artificial intelligence (AI), 4 example, 16, 17
Assistive technologies, 31, 204, 208 grid, 94
Autocomplete attribute, 209, 211, 237 principle, 15
problem, 18, 19
selectors, 20, 21
B syntax, 15, 16
Background gradients, 186–190 Cloud computing, 4
Background-image Color formats
property, 193–196 advantages, 147
Boolean value, 206, 209 alpha channel, HEX, 147
Box shadows property hue/saturation/lightness, 148
266
INDEX
267
INDEX
I R
Icon fonts, 196–197 Radial-gradient() functions, 186
Internet Explorer (IE), 83, 249–250, Red Green Blue Alpha (RGBA), 147
258, 260 Repeating gradients
functions, 190–193
Repeating-linear-gradient()
J, K function, 190, 191, 196
JavaScript, 3, 12, 208, 240, 261 Responsive design strategies, 243
Rotate() function, 167
L
Linear-gradient() function, 186, 190 S
Linear timing function, 163 Scalable Vector Graphics
(SVG), 196–198
Scalable vector icons, 196–198
M, N, O Scale() function, 166
Media queries Scripting elements, 12
building project, 114–116, 118 Search engine optimization
characteristics, 105 (SEO), 31
268
INDEX
Server-side languages, 3 W, X, Y, Z
Sizeable icons, 196
Web application programming
Skew() function, 167
interfaces (APIs), 4
Web browsers, HTML
T, U code, 5, 7
Text-level semantics, 52–56 elements
Text shadows form, 11
color values, 175, 176 multimedia, 10, 11
creating multiple text, 179, 181 scripting, 12
embossed text shadow effect, structural, 8
177, 178 tags, 8
example code, 173 text, 9, 10
HTML file, 174 page structure, 12–14
to prevent, 176 Web development
Timing functions, 163, 165 e-commerce, 2
Transition-delay property, 160 HTML
Transition-delay shorthand building websites, 5
property, 162 DOM, 7
Transition-duration Internet, 1
property, 159 social media platforms, 2
Transitions technologies, 3–5
keyframes, 155 web applications, 1
properties, 158–160 Web typography
shorthand properties, 160–162 animations/transitions, 143
timing functions, 163–165 font stacks, 142
transition-timing-function, 159, 162 text effects/decorations, 142
Twitter, 2 variable fonts, 143
Typography, 123, 142–145 web fonts, 142
websites, 141
Wide Web Consortium
V (W3C), 26, 127
Vendor prefixes, 126–129 Word wrapping, 133–134
269