CSS Web Dev
CSS Web Dev
Table of Contents
INTERNET AND WEB TECHNOLOGY ............................................................................. 1
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
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.
p{
color: blue;
font-family: Arial;
}
This may seem completely foreign, especially the curly brackets, but take another look. Can
you recognize some elements?
Here are the before and after results of the above code snippet:
2
INTERNET AND WEB PAGE AUTHORIZATION
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.
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
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
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.
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>
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.
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>
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;
}
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;
}
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
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.
The element selector selects HTML elements based on the element name. Forexample,
p{
text-align: center;
color: red;
}
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;
}
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;
}
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;
}
/* selected link */
a:active {
color: #0000FF;
}
12
INTERNET AND WEB PAGE AUTHORIZATION
CSS Properties
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
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!
Using the above green as an example, here's a bad color combination (the text is hard to
read!):
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
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:
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:
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:
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;
}
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:
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
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
p{
border-width: medium;
}
p{
border-width: thick;
}
p{
border-width: 8px;
}
p{
border-width: 1.5em;
}
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:
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;
}
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:
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.
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;
}
h1 {
padding: 10px;
}
p{
padding: 10px;
}
30
INTERNET AND WEB PAGE AUTHORIZATION
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
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%;
}
33
INTERNET AND WEB PAGE AUTHORIZATION
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:
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
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
37
INTERNET AND WEB PAGE AUTHORIZATION
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
40
INTERNET AND WEB PAGE AUTHORIZATION
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.
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
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;
}
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;
}
blockquote {
width: 50%;
}
45
INTERNET AND WEB PAGE AUTHORIZATION
Example with a div width of 37.5em and block quote width of 50%
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;
}
}
50
INTERNET AND WEB PAGE AUTHORIZATION
On screens greater than 320px wide, the nav bar should look like this:
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
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:
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
56
INTERNET AND WEB PAGE AUTHORIZATION
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.
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
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;
}
A simple bit of text can be more theatrical with some word spacing. Here's some regular text:
63
INTERNET AND WEB PAGE AUTHORIZATION
#quote {
word-spacing: 1.1em;
}
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. */
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
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