Il 0% ha trovato utile questo documento (0 voti)
13 visualizzazioni

CSS Web Dev

CSS WEB DEVICE NOTES

Caricato da

Hilda Ben
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Il 0% ha trovato utile questo documento (0 voti)
13 visualizzazioni

CSS Web Dev

CSS WEB DEVICE NOTES

Caricato da

Hilda Ben
Copyright
© © All Rights Reserved
Formati disponibili
Scarica in formato PDF, TXT o leggi online su Scribd
Sei sulla pagina 1/ 67

Topic Three

Table of Contents
INTERNET AND WEB TECHNOLOGY ............................................................................. 1

2. CSS (Cascading Style Sheet):........................................................................................ 1

2.1. INTRODUCTION TO CSS (Cascading Style Sheet): ............................................. 1

Advantages of CSS ........................................................................................................... 3

Who Creates and Maintains CSS? ..................................................................................... 4

CSS Versions .................................................................................................................... 4

Methods for adding CSS ................................................................................................... 5

i. Embedded CSS - the <style> element...................................................................... 5

ii. Inline CSS - the style attribute ............................................................................. 6

iii. External CSS - the <link> element ....................................................................... 6

2.2 CSS ─ SYNTAX .................................................................................................... 7

Types of Selectors ......................................................................................................... 8

CSS Properties ............................................................................................................ 13

Discover Elements As Boxes ....................................................................................... 17

CSS Comments ........................................................................................................... 64

2.3 CSS ─ MEASUREMENT UNITS ........................................................................ 64


INTERNET AND WEB PAGE AUTHORIZATION

INTERNET AND WEB TECHNOLOGY

2. CSS (Cascading Style Sheet):

2.1. INTRODUCTION TO CSS (Cascading Style Sheet):

HTML is the language that handles the first concern: creating structured content to tell a story.
CSS covers the second concern: customizing the appearance of that content to visually
bring it to life.
CSS stands for Cascading Style Sheets. That's a complicated way of saying that CSS allows
you to set styles.

Styles are like decoration. Imagine saying "I want my website background color to be yellow,
the text up top to be black, the text in the bottom section of the page to be white, the images to
have a bit of space around them, and the whole thing to appear differently on mobile." All of
those colors and spacing and placement is style. You just write it in code, not in English!

You also use CSS to create a layout for your site, such as placing a certain section on the left
of the page, determining the size of the navigation bar that appears at the top of your website,
or making multiple sections appear side-by-side in one row.
CSS controls the way different pieces of content are arranged on websites. For example, the
fact that there is a column with articles on the left of the New York Times and newspaper
sections arranged in a horizontal bar (World, U.S., etc.) is not a coincidence! Developers
created this layout with CSS:

1
INTERNET AND WEB PAGE AUTHORIZATION

New York Times layout

While CSS is very powerful, it depends on HTML. Consider decorating a house. First, you
select your element, like the bedroom walls or living room floor. Then, you specify how it
should look: the dining room walls should be red, or the living room floor should be carpeted.
If an interior designer asked how you want to decorate the dining room, and you just said "Red,"
they wouldn't know what you're talking about. You must say you're talking about the walls
first.
The same is true for HTML and CSS. In some quick examples, let's see what that looks like.

CSS applied to HTML


There are two steps while using CSS to make your HTML look awesome:
 Identify and select the relevant HTML element (ex. paragraph, header, etc).
 Add some styles (specify how it should look).

Let's say we want the text of our paragraph to be blue:

p{
color: blue;
font-family: Arial;
}

This may seem completely foreign, especially the curly brackets, but take another look. Can
you recognize some elements?

 p: refers to the paragraph tag in HTML, which is <p>.


 color: blue: color is a CSS property. Here, we've made the text color blue.
 font-family: this is also a CSS property to set the font of your text. In the example above,
it is set to Arial. We will get into the intricacies of choosing fonts later in the course.
 { }: curly brackets open and close a set of style rules in CSS

Here are the before and after results of the above code snippet:

2
INTERNET AND WEB PAGE AUTHORIZATION

Before (no CSS, just the default HTML appearance)

After (CSS applied to HTML)

By understanding how HTML and CSS play together, you already have a huge leg up for
learning the intricacies of each language. Remember:
1. Write your content in HTML.
2. Decorate you content with CSS.

Advantages of CSS

 CSS saves time - You can write CSS once and then reuse the same sheet in multiple
HTML pages. You can define a style for each HTML element and apply it to as
many web pages as you want.
 Pages load faster - If you are using CSS, you do not need to write HTML tag
attributes every time. Just write one CSS rule of a tag and apply it to all the
occurrences of that tag. So, less code means faster download times.
 Easy maintenance - To make a global change, simply change the style, and all the
elements in all the web pages will be updated automatically.

3
INTERNET AND WEB PAGE AUTHORIZATION

 Superior styles to HTML - CSS has a much wider array of attributes than HTML,
so you can give a far better look to your HTML page in comparison to HTML
attributes.
 Multiple Device Compatibility - Style sheets allow content to be optimized for
more than one type of device. By using the same HTML document, different
versions of a website can be presented for handheld devices such as PDAs and
cellphones or for printing.
 Global web standards – Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it’s a good idea to start using CSS in all the HTML
pages to make them compatible with future browsers.

Who Creates and Maintains CSS?

CSS is created and maintained through a group of people within the W3C called the CSS
Working Group. The CSS Working Group creates documents called specifications. When a
specification has been discussed and officially ratified by the W3C members, it becomes a
recommendation.
These ratified specifications are called recommendations because the W3C has no control over
the actual implementation of the language. Independent companies and organizations create
that software.
NOTE: The World Wide Web Consortium or W3C is a group that makes recommendations
about how the Internet works and how it should evolve.

CSS Versions

Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in


December 1996. This version describes the CSS language as well as a simple visual formatting
model for all the HTML tags.

Among its capabilities are support for- Font properties such as typeface and emphasis, Color
of text, backgrounds, and other elements.

CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds
support for media-specific style sheets e.g. printers and aural devices, positioning, visual
formatting, interfaces, z-index and new font properties such as shadows and tables.

4
INTERNET AND WEB PAGE AUTHORIZATION

Work on CSS level 3 started around the time of publication of the original CSS 2
recommendation. The earliest CSS 3 drafts were published in June 1999
User Interfaces, Accessibility, Column layout, Mobile Devices, Scalable Vector Graphics

Methods for adding CSS

Style can be delivered to a document by a variety of methods. The method with which style is
connected with a document is referred to as integration. There are a variety of ways to integrate
style, and how you decide to integrate style will depend largely upon what you are trying to
accomplish with a specific document or number of documents.

i. Embedded CSS - the <style> element

Embedding allows for control of a full document. Using the style element, which you place
within the head section of a document, you can insert detailed style attributes to be applied to
the entire page.
Embedding is an extremely useful way of styling individual pages that may also have other
style methods influencing them. You can put your CSS rules into an html document using the
<style> element. This tag is placed inside the <head>...</head> tags.
<head>
<style type="text/css"
style rules
............
</style>
</head>
Example
<!DOCTYPE html
<html>
<head>
<title>Embedded Style Sample</title>
<style type="text/css" media="screen">
h1 {
color: white;
}
5
INTERNET AND WEB PAGE AUTHORIZATION

</style>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>

ii. Inline CSS - the style attribute

The inline integration method allows you to take any tag and add a style to it. Using inline style
gives you maximum control over a precise element of a web document, even just one character.
Say you want to control the look and feel of a specific paragraph. You could simply add a
style="x" attribute to the paragraph tag, and the browser would display that paragraph using
the style values you added to the code.
Here is the generic syntax:
<element style="...style rules....">
Example:
<!DOCTYPE html>
<html>
<head>
<title>Inline Style Sample</title>
</head>
<body>
<h1 style="color: white" >Welcome!</h1>
</body>
</html>
NOTE: Inline style is useful for getting precise control over something in a single document,
but because it only applies to the element in question, you most likely won’t be using inline
style as frequently as other integration methods.

iii. External CSS - the <link> element

The <link> element can be used to include an external stylesheet file in your HTML document.
An external style sheet is a separate text file with .css extension.

6
INTERNET AND WEB PAGE AUTHORIZATION

You define all the style rules within this text file and then you can include this file in any
HTML document using <link> element.
Here is the generic syntax of including external css file:
<head>
<link type="text/css" rel="stylesheet" href="..." />
</head>

2.2 CSS ─ SYNTAX

A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. A style rule is made of three parts:
 Selector: A selector is an HTML tag at which a style will be applied. This could be any
tag like <h1> or <table> etc.
 Property: A property is a type of attribute of HTML tag. Put simply, all the HTML
attributes are converted into CSS properties. They could be color, border, etc.
 Value: Values are assigned to properties. For example, color property can have the
value either red or #F1F1F1 etc.
Imagine you are ordering in a Thai restaurant. A custom order would involve selecting the item
you want to modify and changing its properties. Let's say you want red curry that's extremely
spicy, and you want them to hold the onions. Translated to CSS, your order might look like
this:

curry {
color: red;
spice-level: extreme;
onions: none;
}

Of course, you won't be working with food items in CSS!

Here is a real example that you might see in CSS that involve selecting HTML elements; not
Thai food!

p{

7
INTERNET AND WEB PAGE AUTHORIZATION

color: white;
background-color: blue;
font-family: Arial;
}

You can put CSS Style Rule Syntax as follows:


selector { property: value }
Example: You can define a table border as follows:
table{ border :1px solid #C00; }
Here table is a selector and border is a property and the given value 1px solid #C00 is the value
of that property.

Types of Selectors
Selectors are used to declare which part of the markup a style applies to, a kind of match
expression.
Types of selectors
a. Class selectors (.content, .menu)
b. ID selectors (#wrapper, #sidebar)
c. Tag selectors (body, p, div, a)
d. Descendant selectors
e. Universal selectors
f. CSS grouping selectors
g. CSS Pseudo Selectors
*The selector is normally the html element you want to style
*Selectors should never start with a number, nor should they have spaces in them

a. The Class Selectors

The class selector is used to specify a style for a group of elements. Unlike the id selector,
the class selector is most often used on several elements. This allows you to set a particular
style for many html elements with the same class.
The class selector uses the html class attribute, and is defined with a "." All the elements having
that class will be formatted according to the defined rule.
.black {

8
INTERNET AND WEB PAGE AUTHORIZATION

color: #000000;
}
This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example:
h1.black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to a given element. Consider the following
Example:
<p class="center bold">
This paragraph will be styled by the classes center and bold.
</p>

b. The ID Selectors

You can define style rules based on the id attribute of the elements. All the elements having
that id will be formatted according to the defined rule.
#black {
color: #000000;
}
This rule renders the content in black for every element with id attribute set to black in our
document. You can make it a bit more particular. For example:
h1#black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendant
selectors. For example:
#black h2 {
color: #000000;
}

9
INTERNET AND WEB PAGE AUTHORIZATION

In this example, all level 2 headings will be displayed in black color when those headings
will lie within tags having id attribute set to black.

c. Tag selectors (body, p, div, a)

The element selector selects HTML elements based on the element name. Forexample,
p{
text-align: center;
color: red;
}

d. The Descendant Selectors

Suppose you want to apply a style rule to a particular element only when it lies inside a
particular element. As given in the following example, the style rule will apply to <em>
element only when it lies inside the <ul> tag.
ul em {
color: #000000;
}

e. Universal Selectors

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

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

*{
text-align: center;
color: blue;
}

f. The CSS Grouping Selector


The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style
definitions):

10
INTERNET AND WEB PAGE AUTHORIZATION

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

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

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

It will be better to group the selectors, to minimize the code. To group selectors, separate
each selector with a comma.
Example
In this example we have grouped the selectors from the code above:

h1, h2, p {
text-align: center;
color: red;
}

g. CSS Pseudo Selectors

What are Pseudo-classes?


A pseudo-class is used to define a special state of an element. For example, it can be used
to:

 Style an element when a user mouses over it


11
INTERNET AND WEB PAGE AUTHORIZATION

 Style visited and unvisited links differently


 Style an element when it gets focus

Syntax
The syntax of pseudo-classes:
selector:pseudo-class {
property: value;
}
Anchor Pseudo-classes
Links can be displayed in different ways:

Example
/* unvisited link */
a:link {
color: #FF0000;
}

/* visited link */
a:visited {
color: #00FF00;
}

/* mouse over link */


a:hover {
color: #FF00FF;
}

/* selected link */
a:active {
color: #0000FF;
}

12
INTERNET AND WEB PAGE AUTHORIZATION

CSS Properties

CSS control many style properties of an element such as:


 Coloring
 Size
 Position
 Visibility
 Many more: (e.g. p: { text-decoration: line-through; })

CSS - Colors

Color has a way of livening up even the most drab of web experiences. It also allows you
to create unique brand identity for a client or for your own business!
Typically, CSS colors are used to set a color either for the foreground of an element (i.e.,
its text) or for the background of the element. They can also be used to affect the color of
borders and other decorative effects.
You can specify your color values in various formats. Whichever way you choose to set
colors, be consistent.
Following table lists all the possible formats

We'll check out the following ways to set color:


 Hex codes
 RGB values
 Color names
 HSL values

13
INTERNET AND WEB PAGE AUTHORIZATION

Here's the green we'll be working with as an example to explore each way of expressing
color!

Our example green


Accessibility
One quick note before we jump into ways of setting color: make sure to use color schemes
that are easily readable. This means choosing sufficiently high contrast color combinations
so that even people who can't see well can still tell letters and content apart from each other
on your page.
Using a high-contrast combination helps readability:

Using the above green as an example, here's a bad color combination (the text is hard to
read!):

Bear this in mind as you set colors in CSS!


HEX codes
Hex codes are widely used to set color in CSS. A hex code is a 6-digit string of numbers
and letters that represents the red, green, and blue values of a color in hexadecimal
format. Whoa! Sounds complicated.

14
INTERNET AND WEB PAGE AUTHORIZATION

The good news is you don't really need to think about how the code are set. Hex codes are
really easy to find by using a color picker tool. There are many available online, such as
this one: https://htmlcolorcodes.com/color-picker/
By using a color picker tool, you will often immediately see a set of characters starting
with #. Think no further. This is the hex code for your selected color.
Here are some sample hex codes of nice colors (including our green in the example above).

To set a heading's color to the first green above via hex code, we'd write the following
HTML and CSS:
<h1 id="hex">Color via hex code: #1BDA76</h1>
h1 {
color: #1BDA76;
}
See the "#1BDA76" in the CSS statement? That's the hex code! Here's our result:

Result
RGB values
Each pixel on your computer screen is a tiny light that expresses color by adapting levels
of red, blue, and green light. "RGB" as a way to set color therefore stands for "Red, Green,
Blue"!
An RGB value in CSS is formatted as follows: rgb(red, green, blue); Luckily, color pickers
will often give you the RGB values in addition to a hex code. The green above in RGB is
27, 218, 118. This means:
 our color's "red" value is 27.

15
INTERNET AND WEB PAGE AUTHORIZATION

 our color's "green" value is 218.


 our color's "blue" value is 118.
Let's set a heading to the same green as above via an RGB value:
h1 {
color: rgb(27, 218, 118);
}

Result
Voilà! It's the same green, just expressed differently.
Sometimes, you will see rgba() colors that include a fourth value as well. The fourth value
controls opacity (e.g. how transparent it is). To create a color that is halfway opaque, you
would write color: rgba(27, 218, 118, 0.5);

Color names
In the previous examples where you learned the introduction to CSS we set color as simple
color names in the paragraph example. There are 147 defined color names in CSS. While
they might seem practical, they're actually very limiting.
Some even have obscure names, like PapayaWhip or LemonChiffon. This is cool if you're
into desserts but is not very useful in your codebase! This means we can't set an exact
match to our green above using a simple color name. The closest we can get is probably
"LightGreen":
h1 {
color: LightGreen;
}
Here's what we end up with:

Result
It's fine but not an exact match. Find a full list of all CSS color names online, but don't
count on using them often.

16
INTERNET AND WEB PAGE AUTHORIZATION

HSL values
Recent updates to CSS have added a new way to set color values called "HSL." This stands
for hue, saturation, and lightness. It is intended to be a more human-understandable
format; if you understand the 360 degrees of a color wheel, you can easily guess at what a
color code might be (which is not the case with a hex code or RGB value).
The first value, hue, represents where the color is in a color wheel (which is circular, so
the maximum value is 360).
The second value, saturation, represents the amount of grey in the color you select. You
can think of this as the vibrancy of the color. It's expressed as a percentage from 0% to
100%.
The third value, lightness, represents the amount of black in a color. It's also expressed as
a percentage from 0% to 100%.
The HSL values for our green above are 149, 88%, and 48%.

h1 {
color: hsl(149, 88%, 48%);
}
By stacking all ways of setting the green above, here are the results. All are identical except
for the green set via color name, which is less specific than using a hex code, RGB, or HSL
value:

Four ways of setting colors

Discover Elements As Boxes

Web pages are composed of elements like headings, paragraphs, images, articles, and
more. These elements are created in HTML, and their appearances are customized in CSS.

17
INTERNET AND WEB PAGE AUTHORIZATION

Customizing an element's appearance often means setting where it lives on the page
and how much space it takes relative to other elements. In other words, the layout of your
web page can make the difference between a great, well-designed user experience and a
confusing one!
In order to understand the extent to which layouts are important, consider which of the
following looks like a more realistic website layout:

Layout A (default element appearance, no layout customization)

Layout B (minor layout customization)


I'll bet you picked layout B! There are several great reasons to do so, including:
 less unnecessary white space between elements
 increased space between the text and the edge of its background color
 two blocks that appear next to each other instead of everything stacking vertically.

18
INTERNET AND WEB PAGE AUTHORIZATION

Elements as boxes
Creating layouts requires complete understanding of one key concept: All HTML
elements can be considered as boxes. In CSS, the term "box model" is used when
talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists
of: margins, borders, padding, and the actual content. The image below illustrates the box
model:

Explanation of the different parts:

Element - The content of the box, where text and images appear
Padding - Clears an area around the content. The padding is transparent
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between
elements.
Example
Demonstration of the box model:
This <div> element will have a total width of 470px:
div {
width: 300px;
border: 15px solid green;
padding: 50px;

19
INTERNET AND WEB PAGE AUTHORIZATION

margin: 20px;
}

Here is the calculation:


300px (width) of the element
+ 100px (left + right padding)
+ 30px (left + right border)
+ 40px (left + right margin)
= 470px
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border +
left margin + right margin

The total height of an element should be calculated like this:


Total element height = height + top padding + bottom padding + top border + bottom
border + top margin + bottom margin

By default, that box will be just big enough to contain the element itself. In the image below,
I've added a background color to different HTML elements so you can see the boxes that
contain each element.

Notice that some boxes (like the purple box for the first heading) span the entire width of the
page, whereas the light green box containing the link is only as big as the link itself! Boxes
behave differently depending on the element type.

20
INTERNET AND WEB PAGE AUTHORIZATION

Let's look again at the first image from above and the code behind it:
HTML
<h1>This is a heading.</h1>
<h3>This is another heading.</h3>
<p id="one">This is a paragraph.</p>
<ul>
<li>This</li>
<li>Is</li>
<li>A</li>
<li>List.</li>
</ul>
<p id="two">This is another paragraph with a <a href="#">link</a> in it.</p>
CSS
body {
color: #fff;
font-family: Futura;
padding: 20px;
}
h1 {
background-color: #A4036F;
}
h3 {
background-color: #048BA8;
}
#one {
background-color: #16DB93;
}
ul {
background-color: #EFEA5A;
}
#two {
background-color: #FE5E41;
}

21
INTERNET AND WEB PAGE AUTHORIZATION

a{
background-color: #E6F6C2;
color: #000;
}

Why do the boxes behave differently depending on the element type? Some of the elements
are block-level elements and some are inline elements as we have discussed in the
previous topic. Block-level elements span the entire width of their containing element,
whereas inline elements are only wide enough for their contents.
Equally important for layouts is the notion of a containing element. We'll talk a lot about
"containing elements" or "containers" in this course. A containing element is one element
that contains others.

CSS Borders

Much like you can frame a picture and hang it on your wall, you can add borders to your
HTML elements that frame them visually.
This element has an orange border, for example:

Element with an orange border

There are many different ways to adapt a border's style! Here are just some examples of
what web borders in CSS might look like (you'll see all of them in this chapter!):

22
INTERNET AND WEB PAGE AUTHORIZATION

So many border options!


In CSS, you can control a border's:
 width (thin, wide, 5px, etc.)
 style (solid, dashed, etc.)
 color (hex code, RGB value, etc.)
This results in a ton of border options that can spice up your elements.
You can also create borders around elements in either a shorthand or longhand way,
depending on your preference. We'll explore how to do both in this chapter!
Border syntax

Before we look at border value examples, there are two general ways to set borders:
 a longhand way where you list out each value in a different property (ex. border-
width, border-style, and border-color ).
 a shorthand way where you combine all values into one property called border
Let's look at the shorthand way first. You can set borders in CSS using one simple property
called border. In it, you will specify three border properties in the following order:
 width
 style
 color
Here are three quick examples of setting borders using the shorthand method:
h1 {
border: 5px solid red;
}

h3 {
border: 1em dashed #A4036F;

23
INTERNET AND WEB PAGE AUTHORIZATION

p{
border: thick dotted rgb(22, 219, 147);
}

You can also set borders the longhand way by specifying all border values as different
properties. Here are the same three examples from above, written out the longhand way:
h1 {
border-width: 5px;
border-style: solid;
border-color: red;
}

h3 {
border-width: 1em;
border-style: dashed;
border-color: #A4036F;
}

p{
border-width: thick;
border-style: dotted;
border-color: rgb(22, 219, 147);
}

You'll often set borders the shorthand way because it's faster and more concise. In the
below sections, though, we'll write each property out the longhand way for the sake of
clarity.
Setting border width
Border widths can be set as either pixel values, em/rem values, or using a word that CSS
has already pre-defined, like "thin," "medium," or "thick."
As you saw above, the width will be the first value in the shorthand way to specify borders.
However, it can also be set on its own with the border-width property.
I most often set borders using pixels, but you could also use em/rem in order to keep the
border width proportional to the text. If an element has a font-size of 16px, setting a border
width of 1em means the border will be 16px wide. If a user has their font preferences set
to a higher size, though, and you set your border size in em/rem, your border will grow or
shrink accordingly (which would not happen with a pixel value).

24
INTERNET AND WEB PAGE AUTHORIZATION

Different border widths


p{
border-width: thin;
}

p{
border-width: medium;
}

p{
border-width: thick;
}

p{
border-width: 8px;
}

p{
border-width: 1.5em;
}

Setting border style


In reality, you'll most often specify a "solid" border style. Depending on a certain style
you're going for, though, you might choose a different border aesthetic. Here is the full list
of possible options for setting borders in CSS:
 solid
 dashed
 dotted
 double
 groove
 hidden
 none
 ridge
 inset
 outset

25
INTERNET AND WEB PAGE AUTHORIZATION

The following image represents each border style, except "hidden." Based on the list above,
guess which border style corresponds to each image below. Check the CSS code
following the image to find out if you're right:

All possible border styles


p{
border-style: solid;
}

p{
border-style: dashed;
}

p{
border-style: dotted;
}

p{
border-style: double;
}

p{
border-style: groove;
}

p{
border-style: none;
}

26
INTERNET AND WEB PAGE AUTHORIZATION

p{
border-style: ridge;
}

p{
border-style: inset;
}

p{
border-style: outset;
}
You can even set specific border styles per side by using property names that specify the
top, bottom, left, or right border:
p{
border-top-style: dotted;
border-bottom-style: dashed;
border-left-style: solid;
border-right-style: double;
}

This usually looks a little goofy, though:

Different border styles per side


Setting border color
Set border colors the same way you set most colors in CSS, using:
 hex codes
 RGB or RGBA values
 color names
 hsl values
Like we saw with border style, you can even set a different border color per side by
specifying whether you're talking about the top, bottom, right, or left border color.
p{

27
INTERNET AND WEB PAGE AUTHORIZATION

border-top-color: #16DB93;
border-bottom-color: #A4036F;
border-left-color: #EFEA5A;
border-right-color: #FE5E41;
}
The result looks like this:

Different border colors per side


Setting border radius
Lastly, you can also set rounded borders by using a property called border-radius using
em/rem values, pixels, or percentages:
p{
border-radius: 5px;
}

Rounded corners via border radius


Despite all the fancy things you can do with borders, I advise you to keep your borders
simple so that users can focus on the content itself.
Now, you may be wondering how to set additional space in between text and its borders.
This often gives elements more room to breathe. Compare the left and right texts to see the
difference:

Preview of padding, the subject of our next discussion


CSS Padding

28
INTERNET AND WEB PAGE AUTHORIZATION

You'll often want the border of an element to be pushed out from the element's contents
itself. Borders can visually suffocate your elements, and it would be nice to let them
breathe!
Padding is the space between an element's contents and border. It is still within the element
itself, not around it.

An element's padding and border


Unlike many other CSS properties, padding is not inherited from parent elements. You
must explicitly set it on the elements where you want it.
How to set padding
Setting padding is as simple as giving the padding property a space value via pixels,
em/rem and percentage.

Here's the example we'll use in this course, which currently has no padding
HTML
<h1>Desserts are good!</h1>
<p>Cupcake ipsum dolor sit amet caramels marshmallow powder chocolate bar. Jujubes
halvah chocolate sweet roll croissant muffin muffin. Apple pie jelly beans caramels apple
pie pudding sugar plum candy icing. Soufflé marshmallow icing jelly brownie donut icing
muffin halvah. Bear claw powder chocolate topping chupa chups. Cotton candy pie halvah.

29
INTERNET AND WEB PAGE AUTHORIZATION

Gummies cake fruitcake cotton candy candy pudding cupcake brownie. Chupa chups
danish brownie gummi bears dragée.</p>
CSS
body {
font-family: Futura;
}
h1 {
color: #B33C86;
border: 10px solid #B33C86;
}
p{
color: #190E4F;
border: 5px solid #190E4F;
}

Let's add some padding!

Setting padding in pixels


Adding padding in pixels is a great way to set padding that never changes. Regardless of
the text size the user has set, the padding will always be shown at the same size. Select
your element, declare a padding property, and set it to a numerical value in pixels:

h1 {
padding: 10px;
}
p{
padding: 10px;
}

30
INTERNET AND WEB PAGE AUTHORIZATION

Example with 10px of padding

Setting padding in em/rem


You can also set padding as an em or rem value. The padding value will then be relative to
the element's text size. If an h1 has a font-size of 32px, 1em of padding would be 32px. If
a p has a font-size of 16px, 1em of padding would be 16px.

Setting padding with a relative unit like em or rem means that if a user has a default font
size set in their browser, your design will be relative to that font size. This could allow for
more design consistency.

h1 {
padding: 0.5em;
}

p{
padding: 1em;
}

31
INTERNET AND WEB PAGE AUTHORIZATION

Example with 0.5em and 1em of padding

Setting padding via percentages


You can also set padding as a percentage value. The percentage is relative to the width of
the containing element. This is a bit abstract, so stick with me.
Take the following example of a paragraph within the body of your page:
<body>
<p>My paragraph</p>
</body>
Say that:
the body of the page is 850px wide.
the paragraph inside the body is 300px wide.

If you set padding: 10% on the paragraph element, the paragraph's padding will be 85px
(10% of 850px); not 30px (10% of 300px).
NOTE: Padding percentages are not relative to the width of the element itself; they're
relative to the width of its containing element.
To calculate your ideal padding value as a percentage, here's some easy math:
padding as percentage = desired padding in pixels / width of containing element * 100

32
INTERNET AND WEB PAGE AUTHORIZATION

In our previously used example, a body contains the heading and paragraph. Because the
body is 500px wide, the h1's padding (5%) will be 25px. The paragraph's padding (3%)
will be 15px.
h1 {
padding: 5%;
}
p{
padding: 3%;
}

Example with 5% and 3% padding

Setting multiple padding values


You'll often want to set one vertical padding value and another horizontal padding
value. Let's take the case of buttons; it's a little too intense to have 30px of padding on
every side of a button (top, right, bottom, and left):

33
INTERNET AND WEB PAGE AUTHORIZATION

Too much padding


It would make more sense to have more padding on the left/right sides of the button and
less on the top/bottom sides:

Reasonable padding for a button


You can set top, right, bottom, and left padding values in that order:
p{
padding: 5px 30px 5px 30px;
}

Remember the acronym TRBL (top, right, bottom, left) if you have a hard time
remembering the value order. It sounds like "trouble!"
If your top/bottom values are the same, and your left/right values are the same, you can
also just set two values: one for the top/bottom padding and another for left/right padding.
p{
padding: 5px 30px;
}
Here are different padding values and their results:

Padding values and their results


In the middle example, the same result is achieved in both lines of code!

CSS Margin

You've learned how to set borders around elements in this course so far. You have also
learned how to add space between the element and its border.
What about spacing around elements, though?
Margin is the CSS property that controls spacing between elements. In this diagram, see
how it relates to the other layout elements you've seen so far:

34
INTERNET AND WEB PAGE AUTHORIZATION

An element and its padding, border, and margin


An element has padding around it, which is then surrounded by a border, which then has
margins outside of it that determine the space between this element and its neighbor(s).
How to set margins
Margins are similar to padding in that they can be set as:
 pixels
 em/rem values
 percentages that are relative to the width of the containing block.
Margins also can have a value called auto that is useful for centering content.
Let's start with checking out an example using a paragraph and some images:

Example with no margins


You'll notice there's a very small amount of space between each image already. This is
the default space set by the browser when images are placed on new lines in HTML.
Here's the HTML and CSS for the example below:
HTML
<p>Best practices; greenwashing parse collaborative cities revolutionary think tank social
impact agile mobilize. Relief replicable citizen-centered; the resistance inspire.</p>
<img src="https://images.unsplash.com/photo-1481402665672-0a280f0e9845?ixlib=rb-
0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=f572b
8be919dd72727de32df24f7fcfe">

35
INTERNET AND WEB PAGE AUTHORIZATION

<img src="https://images.unsplash.com/photo-1482148454461-aaedae4b30bb?ixlib=rb-
0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=150b
97749895691afb8e046df5bce838">
<img src="https://images.unsplash.com/photo-1446714276218-bd84d334af98?ixlib=rb-
0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ&s=b1d6
96434ea0bb834407b989b34b2f8b">
CSS
body {
width: 700px;
text-align: center;
}
p{
font-family: 'Minion Pro';
background-color: black;
color: white;
padding: 10px;
}
img {
width: 150px;
border: 10px solid black;
}

Now that you've seen the HTML and CSS for our example, let's go ahead and set some
margins!
Setting margins via pixels
Adding margins in pixels is a great way to set margins that never change, regardless of
the size of the element or the text size involved.
Let''s select the image element, declare the margin property, and set it to 20 pixels:
img {
margin: 20px;
}

36
INTERNET AND WEB PAGE AUTHORIZATION

Example with a margin of 20px


By specifying one single value, you set the top, bottom, right, and left margins all to the
same amount. Now, 20px of margin has been added to the top, left, bottom, and right of
each image element. This means that there's more space between:
 the paragraph and the images, which is a result of the image's top margin value
 the images themselves, which is a result of the image's left and right margin values
Setting margins in em/rem
You can also set margins using em or rem values. The margin value will then be relative
to the element's text size. If an h1 has a font-size of 32px, a 1em margin would be 32px.
If a p has a font-size of 16px, a 1em margin would be 16px.
Setting margin with a relative unit like em or rem means that if a user has a default font
size set in their browser, your design will be relative to that font size. This could allow for
more design consistency.
In our tree image example, the default body text size of 16px is applied (since images don't
really have their own text size). Setting a 1em margin will result in a margin of 16px:
img {
margin: 1em;
}

Example with a margin of 1em

37
INTERNET AND WEB PAGE AUTHORIZATION

Setting margins via percentages


You can also set margins as percentage values. Like we saw in the last chapter for
padding, the percentage is relative to the width of the containing element.
Take the following example of a paragraph within the body of your page:
<body>
<p>My paragraph</p>
</body>
Say that:
 the body of the page is 850px wide.
 the paragraph inside the body is 300px wide.
If you set margin: 10% on the paragraph element, the paragraph's margin will be 85px
(10% of 850px); not 30px (10% of 300px).
Margin percentages are not relative to the width of the element itself; they're relative to the
width of its containing element.
To calculate your ideal margin value as a percentage, here's some easy math:
margin value as percentage = desired margin in pixels / width of containing element
* 100
In our tree image example, a body contains the paragraph and three images. Because the
body is 700px wide, setting a margin of 1% will result in a margin of 7px:
img {
margin: 1%:
}

Example with a margin of 1%


Setting multiple margin values
You'll sometimes want to set top/bottom margins that are different than the left/right
margins.
You can therefore set top, right, bottom, and left margin values in that order:
img {
38
INTERNET AND WEB PAGE AUTHORIZATION

margin: 0px 30px 0px 30px;


}

Example with multiple margin values

Remember the acronym TRBL (top, right, bottom, left) if you have a hard time
remembering the value order. It sounds like "trouble!"
If your top/bottom values are the same, and your left/right values are the same, you can
also just set two values: one for the top/bottom margins and another for left/right margins.
img {
margin: 0px 30px;
}
Why is there still some space between the paragraph and the images in the example above,
even though the margin is 0?
Good question. Default spacing between elements can be tricky to control. That space is
the paragraph's default margin that you didn't specify; paragraphs have 16px of margin
around them by default.
In order to get rid of that space, you'd have to work on the paragraph's margins or set a
negative top margin value for the images (yes, negative values are possible!):
img {
margin: -16px 30px 0px 30px;
}
Collapsing margins
Margins exhibit one unusual feature: vertical margins collapse.
Let's say you have the following elements stacked on top of each other:
 one element that has a bottom margin of 30px
 one element that has a top margin of 20px
The vertical margin between them seems like it would be 50px. After all, 20 + 30 = 50. In
reality, the vertical margin between them will be 30px. When there are two different
vertical margin values touching each other, only the largest of the two will be kept. This
applies to block elements.

39
INTERNET AND WEB PAGE AUTHORIZATION

HTML
<p id="one">Best practices; greenwashing parse collaborative cities revolutionary think
tank social impact agile mobilize. Relief replicable citizen-centered; the resistance
inspire.</p>

<p id="two">
Mobilize strategize academic thought leadership collaborative consumption social return
on investment shine. Parse problem-solvers changemaker, systems thinking empathetic
society.</p>
CSS
one {
margin-bottom: 30px;
}

#two {
margin-top: 20px;
}
Result

Example with a margin of 30px because of collapsing


Auto
Setting left and right margin values to auto will often center an element on your page.
However, you must also declare a width for the element.
We will cover widths in more detail in the next course chapter.
If I take paragraph two from the previous example and set its width to 300px, you'll notice
it is not centered on the page:
#two {
width: 300px;
}

40
INTERNET AND WEB PAGE AUTHORIZATION

Second paragraph is narrower and not centered


By setting the left and right margins to auto, the paragraph moves to the center of its
containing element (in this case, the body of the page):
#two {
width: 300px;
margin: 30px auto;
}

Left/right margins set to auto center the paragraph

CSS Height and Width

Every element has a width and a height that can greatly affect its appearance on your web
page. Element widths and heights can be controlled in order to create large header images,
stacked paragraphs, content columns, and more.
An element has a default width and height that are just enough to hold its contents. For
example, a paragraph element that contains 5 words will be just wide enough to hold those
five words and just tall enough for the font size of those words.
Setting a new width or height property can make an element be just as wide or tall as you
want it to be. To make an element an even 200px wide and 200px tall, you could set:
element {
width: 200px;
height: 200px;

41
INTERNET AND WEB PAGE AUTHORIZATION

}
Padding and borders are added onto the width and height of the element,
however. Adding 10 pixels of padding and a 3px border makes any element take up more
space.

An element and its border, padding, margin, width, and height

Even if you set a width of 200px on an element, the additional padding and border would
make its width actually 226 pixels on the page (200px width + (210px for the padding) +
(23px for the borders)).
This is probably the wonkiest behavior to consider when dealing with widths. With one
line of code, you can override this behavior:
element {
box-sizing: border-box;
}
By setting the box-sizing property to border-box on any element, you declare that its
padding and borders should be included in the width of the element. In the above scenario,
the element would only be 200px wide total — including padding and borders.
The default value of the box-sizing property is content-box. There are only two possible
values for the box-sizing property.
With that in mind, we'll shortly explore the various ways to set widths. We'll use a slightly
more complicated example in order to show the various ways in which width can be set to
achieve a desired effect.
In our example, we have a div that has a class of "main" that contains a heading, a
paragraph, and several block quotes. The div has a dotted border, and the block quotes
have a light green background.
Here's the starter example and its code:

42
INTERNET AND WEB PAGE AUTHORIZATION

Example with no defined width or height


HTML
<div class="main">
<h1>Buy our products</h1>
<p>We are the leading worldwide manufacturer of paintbrushes and pride ourselves on
the highest bristle quality possible. Check out what our customers have to say:</p>
<blockquote>"Amazing brushes! My painting career wouldn't be the same without
them." - John</blockquote>
<blockquote>"An artist is only as good as her tools. Thanks, ABC, for a great product."
- Sarah</blockquote>
<blockquote>"I've never used such strong brushes!" - Linda</blockquote>
</div>
CSS
body {
font-family: Avenir, Arial, sans-serif;
text-align: center;
}
.main {
border: 10px dotted black;
padding: 20px;
margin: 0px auto;
}
h1 {
margin: 0px;
}
blockquote {

43
INTERNET AND WEB PAGE AUTHORIZATION

padding: 20px;
background-color: lightgreen;
border-radius: 10px;
margin: 10px auto;
text-align: center;
}
For the sake of simplicity, we'll work with widths in the practical example. You'll likely
work with them more than heights. Just remember all the same sizing rules apply to heights,
too.
Setting width and height in pixels
As you saw in previous chapters about margins, borders, and padding, widths and heights
can also be set in pixels. Setting a width or height in pixels means that the width or height
will always be the same, regardless of the screen size from which the page is viewed. Be
careful with this!
Setting a width of 600px on the main div will reduce its width and the width of its child
elements automatically so that everything still fits inside:
.main {
width: 600px;
}

Example with a width of 600px

The div is centered on the page because it has a defined width and has its left/right margins
set to auto. Remember that from last chapter?
Setting widths in em/rem

44
INTERNET AND WEB PAGE AUTHORIZATION

When an element's width or height is set in em or rem, the measurement will be equal to
the element's font size. For example, if an element's font size is 16px, 1em of width would
be equal to 16px.
Because main div's font size is the default 16px, we'd have to set its width to 37.5em in
order to achieve a width of 600 pixels (because 600/16 = 37.5).
.main {
width: 37.5em;
}

Example with a width of 37.5em


Setting heights and widths as percentages
When an element's width or height is set as a percentage, the value will be relative to the
width or height of the containing block. Let's say a div is 700px wide. A paragraph inside
the div with a width of 50% would ultimately be 350px wide.
We most recently set the width of our div above to 37.5em. Let's keep that value and set
the block quote widths to 50%. The block quotes will be reduced to half the width of the
main div.
.main {
width: 37.5em;
}

blockquote {
width: 50%;
}

45
INTERNET AND WEB PAGE AUTHORIZATION

Example with a div width of 37.5em and block quote width of 50%

Minimum and maximum widths and heights


Many websites are responsive now, which means that they respond depending on a user's
screen size. For example, if you're on your computer and gradually reduce the size of your
browser window while on KIUT website, you'll notice that most elements get smaller as well.
You may want to set values that never let an element's width or height go above or below a
certain value. The min-width, max-width, min-height, and max-height properties are good
for this.
The max-width and max-height properties will ensure that an element is never wider or taller
than the value you set, even if there's enough room on the page for it to take up more space.
The min-width and min-height properties will ensure that an element is never narrower or
shorter than the value you set, even if the browser window is too small to display the whole
element.

Recap
 Use the height and width properties to size elements in pixels, em/rem, or percentages.
 Padding and borders are added to the height and width; to include them in the overall
size of the element, use the box-sizing property and set it to border-box.
 Use max-width, max-height, min-width, and min-height to ensure that elements never
go above or below a certain size.
Set media queries for different devices

When writing CSS, there's one thing to be particularly concerned about: visitors' screen
resolutions. The space or number of pixels wide vary from one screen to another.

46
INTERNET AND WEB PAGE AUTHORIZATION

This information is important when you build a design: how should your website be displayed
for different screen resolutions? If you have a widescreen, you may forget that some people
browse with smaller screens. Not to mention the browsers of smartphones, which are even less
wide.
This is where media queries come in. These are the rules to be applied to change the design of
a website based on the screen's characteristics! Using this technique, we can create a design
that automatically adjusts to each visitor's screen!
Implementation of media queries
Media are not new properties but rather rules that can be applied under certain conditions.
Specifically, you'll be able to say, "If the visitor's screen's resolution is less than a certain value,
then apply the following CSS properties." This allows you to change the website's appearance
under certain conditions. You can increase the text size, change the background color, position
your menu differently with certain resolutions, etc.
Contrary to what one might think, media queries are not just about screen resolutions. You can
change your website's appearance based on other criteria, such as screen type (smartphone,
TV, projector, etc.), number of colors, screen orientation (portrait or landscape), etc. There
are a great number of possibilities!
Media queries work in all browsers, including Internet Explorer as of version 9 (IE9)
onwards.
Applying a media query
Media queries are thus rules that specify when CSS properties have to be applied. There are
two ways to use them:
 by loading a different.css stylesheet based on the rule (e.g. "If the resolution is less than
1280px wide, load the small_resolution.css") file;
 by writing the rule directly in the usual.css file (e.g. "If the resolution is less than 1280px
wide, load the CSS properties below").
Loading a different stylesheet
You remember the <link /> tag which, in HTML code, loads a .css file?
<link rel="stylesheet" href="css/style.css" type="text/css">
You can add a media attribute in which we're going to write the rule to be applied for the file
to be loaded. This is known as making a media query. For example:
<link rel="stylesheet" media="screen and (max-width: 1280px)"
href="css/small_resolution.css" type="text/css">

47
INTERNET AND WEB PAGE AUTHORIZATION

In the end, your HTML code may provide several CSS files: one as default (which is loaded in
all cases) and one or two others which are only charged in addition if the corresponding rule
applies.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css" /> <!-- For everyone -->
<link rel="stylesheet" media="screen and (max-width: 1280px)"
href="small_resolution.css" /> <!-- For those who have a resolution lower than 1280px -->
<title>Media queries</title>
</head>
Loading rules directly in the style sheet
Another technique, which I personally prefer for practical reasons, is to write these rules in the
same CSS file as usual. In this case, we write the rule in the .css file like this:
@media screen and (max-width: 1280px) {
/* Write your CSS properties here */
}
Possible rules
There are many rules for building media queries. I'll only mention the main ones here:
 color: color management (in bits/pixel).
 height: display field height (window).
 width: display field width (window).
 device-height: device height.
 device-width: device width.
 orientation: device orientation (portrait or landscape).
 media: output screen type. A few of the possible values:screen: "conventional" screen;
 handheld: mobile device;
 print: printing;
 tv: television;
 projection: projector;
 all: all types of screens.

48
INTERNET AND WEB PAGE AUTHORIZATION

The prefix min- or max- can be added in front of most of these rules. So min-width means
"Minimum width" and max-height means "Maximum height", etc. The difference
between width and device-width can primarily be seen in mobile browsers for smartphones,
as we'll see later.
The rules can be combined using the following words:
 only: "only";
 and: "and";
 not: "not";
Here are a few examples of media queries to help you understand the principle.
/* On screens with a maximum window width of 1280px */
@media screen and (max-width: 1280px)
/* On all screen types with a window width of between 1024px and 1280px */
@media all and (min-width: 1024px) and (max-width: 1280px)
/* On TVs */
@media tv
/* On all vertically oriented types of screens */
@media all and (orientation: portrait)
Older browsers, including IE6, IE7, and IE8, don't know media queries but are able to
interpret the start of the rule (they can read @media screen, for example). They will thus read
the following CSS properties even if they are not affected by the rule! To avoid this, one trick
is to use the only keyword that these old versions don't know: " @media only screen " does not
cause a bug on older browsers.
Testing media queries
Media queries are mostly used to adapt the website design to different screen widths.
Let's do a very simple test: we're going to change the text size and color if the window is more
or less than 1024 pixels wide. For this test, I'm going to use the second method is to write the
rule directly in the same .css file as usual:
*{
font-family: Helvetica;
}
p{
background-color: blue;
color: white;

49
INTERNET AND WEB PAGE AUTHORIZATION

width: 300px;
padding: 50px;
text-align: center;
margin: 0px auto;
}
/* New rules if the window width is smaller than 1024px */
@media screen and (max-width: 1024px) {
p{
background-color: black;
color: red;
text-transform: uppercase;
}
}

Result when the screen is wider than 1024px

Result when the window is narrower than 1024px


We have added a media query that applies to all screens not wider than 1024px and applies
some color and text changes depending on the screen size.
Practical use of media queries in the design
Changing the text color is nice, but it doesn't really add much. However, using media queries
to change your website's appearance depending on screen resolution is immediately much more
useful. You'll see that you can do whatever you want!
On mobile sites, you'll often see navigation bars stacked vertically instead of horizontally.
Since the smaller screens are narrower, the full horizontal bar can't be shown.
Let's take a basic navigation bar and make its menu items stack upon one another when the
screen size is less than 320px wide (a standard measurement for smartphone screen width).

50
INTERNET AND WEB PAGE AUTHORIZATION

On screens greater than 320px wide, the nav bar should look like this:

Nav bar on wider screen sizes


On screens less than 320px wide, the nav bar should look like this:

Nav bar on narrower screen sizes


Here's the starter code for the horizontal nav bar (no media queries yet):
HTML
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="https://twitter.com">Contact</a></li>
</ul>
</nav>
CSS
nav {
background-color: #E8D7FF;
padding: 10px;
margin: -8px;
}
a{
font-weight: 200;
text-decoration: none;
text-transform: lowercase;
font-family: Helvetica;
color: #151814;
}

51
INTERNET AND WEB PAGE AUTHORIZATION

ul {
text-align: center;
padding: 0px;
}
li {
list-style: none;
display: inline-block;
margin: 0px 20px;
}
We only need to change the CSS rules for the list item (li) elements in order to make them stack
upon one other. We'll change:
 their display property to block instead of inline-block
 their top and bottom margins to 5px so there's some vertical space between each item (this
was not necessary when the items were in one row)
Here's the resultant media query that can simply be placed under all the other CSS code above:
@media all and (max-width: 320px) {
li {
display: block;
margin: 5px 0px;
}
}
Media queries and mobile browsers
As you probably know, the screens of smartphones are much narrower than our usual
computer screens (they're only a few hundred pixels wide). To adapt to this, mobile browsers
display the website by "zooming out" to allow the whole page to be seen. The simulated display
area is called the viewport: it's the width of the mobile phone's browser window.
With media queries, if, in CSS, you target the screen with max-width on a mobile phone, it
will compare the width you specify against the width of its viewport. The problem is that the
viewport changes according to the mobile browser used!

52
INTERNET AND WEB PAGE AUTHORIZATION

Browser Default viewport width

Opera Mobile 850 pixels

iPhone Safari 980 pixels

Android 800 pixels

Windows Phone 7 1024 pixels

An iPhone behaves as if the window were 980 px wide, while an Android behaves as if the
window were 800 px wide!
To target smartphones, it may be better, rather than using max-width, to use max-device-
width: this is the device's width. Mobile devices are not more than 480 px wide, so we can
target mobile browsers only, using this media query:
@media all and (max-device-width: 480px) {
/* Your CSS rules for your mobile phones here */
}
Why not target mobile phones using the handheld media rule?
I can see that you're following: very good! Indeed, we could theoretically target mobile screens
using the handheld media rule... Unfortunately, no mobile browser except Opera mobile
recognizes handheld. They all behave as if they were normal screens (screen). So you can't
really use handheld for mobile phones.
You can change the mobile browser's viewport width with a meta tag to be inserted in the
document header: <head>.
<meta name="viewport" content="width=320" />
You can use this tag to change the way your page content is organized on mobile phones. To
obtain readable render without zooming, you can set the viewport to the same width as the
screen:
<meta name="viewport" content="width=device-width" />
Recap
This was a tough chapter, so let's sum up what we covered:
 Media queries allow the loading of various CSS styles based on certain settings.

53
INTERNET AND WEB PAGE AUTHORIZATION

 There are a large number of settings allowed by media queries: number of colors,
screen resolution, orientation, etc. In practice, they are mostly used to change the
website's appearance for different screen resolutions.
 You create a media query with the @media directive followed by the screen type and
one or more conditions (such as the maximum screen width). The following CSS style
will be enabled only if the conditions are met.
 Mobile browsers simulate a screen width: this is called the viewport.
 Smartphones can be targeted by a rule based on the actual number of pixels displayed
on the screen: max-device-width.
CSS Fonts

Fonts can make your site look unique and attractive. CSS offers you several ways to set fonts;
the way you ultimately do so will depend on your needs.
You probably already know a bunch of fonts you might've used in presentations or at work,
like Times New Roman, Arial, Verdana, etc. Let's even take a step back from there to look at
fonts more basically.
The most common general font types you see online are:
 sans-serif fonts
 serif fonts
 monospace fonts
What do these terms mean? Serif fonts have little ticks ("serifs") on the edges of each letter.
Sans-serif fonts do not. Monospace fonts feature letters that are all the same width.
Compare the three main font types below:

Different font types

54
INTERNET AND WEB PAGE AUTHORIZATION

Pay particular attention to how the first font has smooth edges, whereas the second font has
little feet on the wide of ends of each letter. Comparing the capital T's is a good way to see the
difference.
With these differences in mind, let's see how to set specific fonts.
Font-family property
The most fundamental CSS property to know for setting fonts is font-family.
However, you can't just set its value to any font and assume it'll work for every user. A font
will only display correctly if the user already has it installed on their computer.
That's why the font-family property will often contain multiple values that serve as fallbacks
if a user doesn't have a certain font installed.
To set all the HTML body text (including headings, paragraphs, and everything else) to
Helvetica, you might write this:
body {
font-family: Helvetica, Arial, sans-serif;
}
What's Arial doing in there? Or sans-serif? I thought we just wanted Helvetica!
Helvetica will display just fine if the user has it installed on their machine. Specifying
additional fonts allows for a similar font to be used if the user doesn't have Helvetica installed.
Therefore, the above line of code says, "If the user has Helvetica installed, show that. If they
don't have Helvetica installed, but they DO have Arial installed, show Arial. If not, show
whatever the default sans serif font is on their computer."
If you want to use a font that is more than one word, you must put it in quotation marks, such
as font-family: 'Helvetica Neue'; .
Font combinations
Some distinctive web aesthetics come from combining different font types, like a sans-serif
font with a serif font.
There are some general design rules to follow when combining multiple font types on one page.
1. Don't use more than three different fonts per page. This font combination looks a little
ridiculous because there is just way too much going on:

55
INTERNET AND WEB PAGE AUTHORIZATION

Too many fonts!


That's why it's best to stick with no more than three fonts per page, and it's important to use
them consistently. This brings us to our next rule.
2. Use the same fonts consistently for content types. For example, make all your headings
use the same font, all of your paragraphs use the same font, all your image captions use the
same font, etc. This allows a viewer to follow a pattern of fonts instead of being mentally jarred
every time they see the same content type in a different font.
3. Combine a sans-serif headline with a serif paragraph. Serif fonts allow the eye to travel
easily between letters, since the little ticks ("serifs") guide the eye from one letter to the next.
Sans-serif fonts are more stark and attention-grabbing. That's why a sans-serif headline can
complement a serif paragraph, but using the opposite combination can fatigue your reader.
In this example, you can see that a sans-serif headline with a serif paragraph is more readable
than its opposite:

56
INTERNET AND WEB PAGE AUTHORIZATION

Serif heading with a sans-serif paragraph


If this type of debate interests you, you may be interested in a career in web design! I personally
find such subjects really interesting.
Installing your own fonts
Sometimes, you'll want to use fonts besides the standard ones that are installed on most peoples'
machines. In that case, you'll need to install a custom font and include the font file as part of
your project files.
Nearly an infinite number of fonts are available for download on various websites, such as:
 Font Squirrel: https://www.fontsquirrel.com/
 Google Fonts: https://fonts.google.com/
 Urban Fonts: https://www.urbanfonts.com/
There are also many more websites that offer fonts for a paid download (the above are, in
theory, free).
You'll just want to make sure the fonts you choose are licensed for commercial use. Otherwise,
you can get into intellectual property trouble! Usually, this will be indicated clearly on the font
page.
To include an installed font as part of your project, you need to define a font-face rule (starting
with an @ sign) that defines the font family and the location of the downloaded font file:
@font-face {
font-family: 'Milkshake';
src: url('fonts/milkshake.otf');
}
h1 {
font-family: Milkshake;
}
As you can see, our special font is called Milkshake. We've saved the downloaded font in a file
called "fonts" and told the CSS file to go find it there.

57
INTERNET AND WEB PAGE AUTHORIZATION

Different font file types can work differently depending on the user's browser. If you're
interested in exploring this route, check out this article that explains the difference between
font file types like .eot, .otf, and more: https://creativemarket.com/blog/the-missing-guide-to-
font-formats
CSS Font Sizing

Several units of measurement are available to control font size in CSS:pixels, em, rem,
percentages.

The primary differences between them is how sizing is calculated relative to the overall web
page. There are two options: setting absolute sizes and relative sizes.
Setting absolute sizes means that you define exact size values, like saying you want to make t-
shirts that are sizes 34, 36, 38, 40, and 42.
Setting relative sizes means that you define all values relative to a base value, like saying that
you want to create a t-shirt line with a base size of 34. All sizes will be defined relative to the
size 34. You might say that you want to produce another size that's 2 inches wider than that
base value, a size that's 4 inches wider than that base value, a size that's 6 inches wider than
that base value, and so on. If the base size of 34 is redefined, the other sizes will change as
well.

Let's start defining sizes with pixels (an absolute way to define sizes).
Pixels
Defining a font size using pixels most closely resembles the way you set font sizes in most
other contexts. When working in Word or Google Documents, you choose a font size from a
dropdown list.
This number is defined in a unit called "points" or "pt" for short. It's a good unit for setting font
sizes in print documents.

On web pages, however, you won't use points. You'll use a similar value of measurement called
pixels. A screen is composed of many pixels, and by setting a font size of 12 pixels, you are
saying that you want your text to have a height of 12 pixels.

58
INTERNET AND WEB PAGE AUTHORIZATION

The one downside with defining size by via pixel values is that your elements' sizes are defined
absolutely and are not relative to one another. This can cause strange behavior sometimes on
certain screen sizes or if a user uses custom size settings in their browser.
The default body text size in CSS is 16px. By "body text", we mean the height of paragraph
text. This is the most fundamental text on any website, and 16px is an important number to
keep in mind as you start working with the other units described in this chapter.

ems and rems


An "em" or "rem" (pronounced as one syllable) are very commonly used units of sizing in CSS
because they let you define sizes relative to other elements.
When setting fonts, 1em is equal to the default body (paragraph) text size of 16px. To set a font
size of 32 px, you would use 2em.
The following math will help you set a font sizes in ems:
em = desired element pixel value / parent element pixel value
A rem is similar to an em, except that it doesn't compound. When using ems, if you have an
element at a size of 2em inside another element of 2em, the inner element will be shown at
4em. When using rems, it will still be shown at 2rem.

Percentages
Setting sizes via percentages is similar to setting them using ems. Sizes are defined as relative
to one another, not as absolute values.
The following math will help you set font sizes in percentages:
percent value = em = desired element pixel value / parent element pixel value * 100
Font-size
Use the font-size property in CSS to adjust the size of text using any of the units above.

Once you choose a unit, just be consistent. For example, if you define one font size using ems,
define all font sizes using ems.
We mentioned above that the default text size for body (paragraph) text is 16px. Therefore:

59
INTERNET AND WEB PAGE AUTHORIZATION

Font unit comparison chart


Say you want to make an h1 element larger than its default size, which is 32px, and you want
to increase the paragraph text size to 18px. You can see the smaller size on the left, and the
new, bigger size on the right.

Font size comparison


The 3 different sets of CSS below all result in the same new font sizes:
/* pixels */
h1 {
font-size: 48px;
}
p{
font-size: 18px;

60
INTERNET AND WEB PAGE AUTHORIZATION

}
/* ems */
h1 {
font-size: 3em;
}
p{
font-size: 1.125em;
}
/* percentages */
h1 {
font-size: 300%;
}
p{
font-size: 112.5%;
}
Only the above units of measurement are different. The resultant visual size is the same!
It will take time to comfortably set sizes using pixels, ems, rems, and percentages. As you work
on your own projects, you'll get a feel for each.
Let's check out three more CSS properties that both involve sizing: line-height, letter-spacing,
and word-spacing.
line-height
In school, you may have been asked to submit essays that were single-spaced or double-spaced
(or even 1.5-spaced)!
In CSS, you control the vertical space between lines of text using the line-height property. This
can particularly help with the readability of long paragraphs.
This paragraph is a little tough to read:

61
INTERNET AND WEB PAGE AUTHORIZATION

Tough to read
An increased line height can help. I advise you to start with a line of 1.4em and adjust it as
necessary.

#code-of-conduct {
line-height: 1.4em;
}

Easier to read

letter-spacing
62
INTERNET AND WEB PAGE AUTHORIZATION

Increasing the space between letters is often useful when dealing with headings in all-caps.
You should always give this value in the em or rem unit so it is proportional to the font the user
has set in their browser. The spacing will be added on top of the default spacing.

Notice how the default appearance of an all-caps heading is fairly cramped (see the "C" and
"A" almost touching?).

Cramped letters
A little letter spacing can help this:

h2 {
letter-spacing: 0.08em;
}

Less cramped letters


word-spacing
You won't often need to increase the space between words, but it can be useful for poetic or
literary effect. You should always give this value in the em or rem unit so it is proportional to
the font the user has set in their browser.

A simple bit of text can be more theatrical with some word spacing. Here's some regular text:

Normal space between words


Plus a little bit of word-spacing:

63
INTERNET AND WEB PAGE AUTHORIZATION

#quote {
word-spacing: 1.1em;
}

Added word spacing


With extra space between words, readers focus more on each word, which can increase the
sentences power. Don't do this all the time though, or your pages will be tiring to read!

CSS Comments

Many times, you may need to put additional comments in your style sheet blocks. So, it is
very easy to comment any part in the style sheet. You can simply put your comments inside
/*.....this is a comment in style sheet.....*/.
You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++
programming languages.
Example
/* This is an external style sheet file */
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
/* end of style rules. */

2.3 CSS ─ MEASUREMENT UNITS

CSS has several different units for expressing a length. Many CSS properties take "length"
values, such as width, margin, padding, font-size, etc. Length is a number followed by a length
unit, such as 10px, 2em, etc. A whitespace cannot appear between the number and the unit.
However, if the value is 0, the unit can be omitted.
For some CSS properties, negative lengths are allowed.

64
INTERNET AND WEB PAGE AUTHORIZATION

There are two types of length units: absolute and relative.

Absolute Lengths
The absolute length units are fixed and a length expressed in any of these will appear as exactly
that size. Examples of absolute lengths are cm(centimeters), mm(millimeters), px(pixels),
pt(points), pc(picas)
Absolute length units are not recommended for use on screen, because screen sizes vary so
much. However, they can be used if the output medium is known, such as for print layout.
Relative Lengths
Relative length units specify a length relative to another length property. Relative length units
scales better between different rendering mediums. Examples em, rem, %(percentage).
You need these values while specifying various measurements in your Style rules e.g.
border="1px solid red".
Unit Description Example
p{
Defines a measurement as a percentage relative font-size: 16pt;
% to another value, typically an enclosing element. line-height: 125%;
}
div {
Defines a measurement in centimeters. margin-bottom: 2cm;
cm
}
A relative measurement for the height of a font
in em spaces. Because an em unit is equivalent p {
to the size of a given font, if you assign a font to letter-spacing: 7em;
em
12pt, each "em" unit would be 12pt; thus, 2em }
would be 24pt.
p{
This value defines a measurement relative to a
font-size: 24pt;
font's x-height. The x-height is determined by
ex line-height: 3ex;
the height of the font's lowercase letter x.
}
p{
Defines a measurement in inches. word-spacing: .15in;
in
}

65
INTERNET AND WEB PAGE AUTHORIZATION

p{
Defines a measurement in millimeters. word-spacing: 15mm;
mm
}
Defines a measurement in picas. A pica is p {
equivalent to 12 points; thus, there are 6 picas font-size: 20pc;
pc
per inch. }

66

Potrebbero piacerti anche