全栈学习笔记
HTML
References
Learn HTML: Elements and Structure Cheatsheet | Codecademy
Only content inside the opening and closing body tags can be displayed to the screen.
Understanding HTML hierarchy is important because child elements can inherit behavior and styling from their parent element.
One of the most popular elements in HTML is the <div>
element. <div>
is short for “division” or a container that divides the page into sections.
<div>
s don’t inherently have a visual representation, but they are very useful when we want to apply custom styles to our HTML elements. <div>
s allow us to group HTML elements to apply the same styles for all HTML elements inside. We can also style the <div>
element as a whole.
- The
<em>
tag will generally render as italic emphasis. - The
<strong>
will generally render as bold emphasis.
Let’s review what you’ve learned so far:
- HTML stands for HyperText Markup Language and is used to create the structure and content of a webpage.
- Most HTML elements contain opening and closing tags with raw text or other HTML tags between them.
- HTML elements can be nested inside other elements. The enclosed element is the child of the enclosing parent element.
- Any visible content should be placed within the opening and closing
<body>
tags. - Headings and sub-headings,
<h1>
to<h6>
tags, are used to provide titles for sections of content. <p>
,<span>
and<div>
tags specify text or blocks.- The
<em>
and<strong>
tags are used to emphasize text. - Line breaks are created with the
<br>
tag. - Ordered lists (
<ol>
) are numbered and unordered lists (<ul>
) are bulleted. - Images (
<img>
) and videos (<video>
) can be added by linking to an existing source.
Here are a few more resources to add to your toolkit:
- Preview: Docs HTML, short for HyperText Markup Language, is the foundation of all web pages. It was created by Tim Berners-Lee in 1993 to define the structure of a web page.Codecademy Docs: HTML
- Codecademy Workspaces: HTML
- https://www.youtube.com/watch?v=uxmB8MlO3m8
The <!DOCTYPE html>
declaration provides the browser with two pieces of information (the type of document and the HTML version to expect), but it doesn’t actually add any HTML structure or content.
Anything between the opening <html>
and closing </html>
tags will be interpreted as HTML code. Without these tags, it’s possible that browsers could incorrectly interpret your HTML code.
The <head>
element contains the metadata for a web page. Metadata is information about the page that isn’t displayed directly on the web page. Unlike the information inside of the <body>
tag, the metadata in the head is information about the page itself.
This attribute stands for hypertext reference and is used to link to a path, or the address to where a file is located (whether it is on your computer or another location). The paths provided to the href
attribute are often URLs.
<a href="https://www.wikipedia.org/">This Is A Link To Wikipedia</a> |
The target
attribute specifies how a link should open.
It’s possible that one or more links on your web page link to an entirely different website. In that case, you may want users to read the linked website, but hope that they return to your web page. This is exactly when the target
attribute is useful!
For a link to open in a new window, the target
attribute requires a value of _blank
. The target
attribute can be added directly to the opening tag of the anchor element, just like the href
attribute.
<a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank">The Brown Bear</a> |
Thankfully, HTML allows you to turn nearly any element into a link by wrapping that element with an anchor element. With this technique, it’s possible to turn images into links by simply wrapping the element with an <a>
element.
<a href="https://en.wikipedia.org/wiki/Opuntia" target="_blank"><img src="https://www.Prickly_Pear_Closeup.jpg" alt="A red prickly pear fruit"/></a> |
In order to link to a target on the same page, we must give the target an id
attribute and a unique value like this:
<p id="top">This is the top of the page!</p> |
Let’s review what you’ve learned this lesson:
- The
<!DOCTYPE html>
declaration should always be the first line of code in your HTML files. This lets the browser know what version of HTML to expect. - The
<html>
element will contain all of your HTML code. - Information about the web page, like the title, belongs within the
<head>
of the page. - You can add a title to your web page by using the
<title>
element, inside of the head. - A webpage’s title appears in a browser’s tab.
- Anchor tags (
<a>
) are used to link to internal pages, external pages or content on the same page. - You can create sections on a webpage and jump to them using
<a>
tags and addingid
s to the elements you wish to jump to. - Whitespace between HTML elements helps make code easier to read while not changing how elements appear in the browser.
- Indentation also helps make code easier to read. It makes parent-child relationships visible.
- Comments are written in HTML using the following syntax:
<!-- comment -->
.
Take some time to edit the workspace you created and observe how it changes!
|
|
Table
In HTML, you can add data using the table data element: <td>
.
Let’s review what we’ve learned so far:
- The
<table>
element creates a table. - The
<tr>
element adds rows to a table. - To add data to a row, you can use the
<td>
element. - Table headings clarify the meaning of data. Headings are added with the
<th>
element. - Table data can span columns using the
colspan
attribute. - Table data can span rows using the
rowspan
attribute. - Tables can be split into three main sections: a head, a body, and a footer.
- A table’s head is created with the
<thead>
element. - A table’s body is created with the
<tbody>
element. - A table’s footer is created with the
<tfoot>
element. - All the CSS properties you learned about in this course can be applied to tables and their data.
|
body { |
Introduction to HTML Forms
Forms are a part of everyday life. When we use a physical form in real life, we write down information and give it to someone to process. Think of the times you’ve had to fill out information for various applications like a job, or a bank account, or dropped off a completed suggestion card — each instance is a form!
Just like a physical form, an HTML <form>
element is responsible for collecting information to send somewhere else. Every time we browse the internet we come into contact with many forms and we might not even realize it. There’s a good chance that if you’re typing into a text field or providing an input, the field that you’re typing into is part of a <form>
!
In this lesson, we’ll go over the structure and syntax of a <form>
and the many elements that populate it.
How a Form Works
10 min
We can think of the internet as a network of computers which send and receive information. Computers need an HTTP request to know how to communicate. The HTTP request instructs the receiving computer how to handle the incoming information. More information can be found in our article about HTTP requests.
The element is a great tool for collecting information, but then we need to send that information somewhere else for processing. We need to supply the <form>
element with both the location of where the <form>
‘s information goes and what HTTP request to make. Take a look at the sample <form>
below:
<form action="/example.html" method="POST"> |
In the above example, we’ve created the skeleton for a <form>
that will send information to example.html as a POST request:
- The
action
attribute determines where the information is sent. - The
method
attribute is assigned a HTTP verb that is included in the HTTP request.
Note: HTTP verbs like POST do not need to be capitalized for the request to work, but it’s done so out of convention. In the example above we could have written method="post"
and it would still work.
The <form>
element can also contain child elements. For instance, it would be helpful to provide a header so that users know what this <form>
is about. We could also add a paragraph to provide even more detail. Let’s see an example of this in code:
<form action="/example.html" method="POST"> |
The example above doesn’t collect any user input, but we’ll do that in the next exercise.
Text Input
If we want to create an input field in our <form>
, we’ll need the help of the <input>
element.
The <input>
element has a type
attribute which determines how it renders on the web page and what kind of data it can accept.
The <input>
element has a type
attribute which determines how it renders on the web page and what kind of data it can accept.
The first value for the type
attribute we’re going to explore is "text"
. When we create an <input>
element with type="text"
, it renders a text field that users can type into. Note that the default value of type
is "text"
. It’s also important that we include a name
attribute for the <input>
— without the name
attribute, information in the <input>
won’t be sent when the <form>
is submitted. We’ll explain more about submissions and the submit button in a later exercise. For now, let’s examine the following code that produces a text input field:
<form action="/example.html" method="POST"> |
Here’s a screen shot of how the rendered form looks like on a web page for the Chrome browser (different browsers have different default rendering). When initially loaded, it will be an empty box:
After users type into the <input>
element, the value of the value
attribute becomes what is typed into the text field. The value of the value
attribute is paired with the value of the name
attribute and sent as text when the form is submitted. For instance, if a user typed in “important details” in the text field created by our <input>
element:
When the form is submitted, the text: "first-text-field=important details"
is sent to /example.html
because the value of the name
attribute is "first-text-field"
and the value of value
is "important details"
.
We could also assign a default value for the value
attribute so that users have a pre-filled text field when they first see the rendered form like so:
<form action="/example.html" method="POST"> |
Which renders:
Datalist Input
Even if we have an organized dropdown list, if the list has a lot of options, it could be tedious for users to scroll through the entire list to locate one option. That’s where using the <datalist>
element comes in handy.
The <datalist>
is used with an <input type="text">
element. The <input>
creates a text field that users can type into and filter options from the <datalist>
. Let’s go over a concrete example:
<form> |
Notice, in the code above, we have an <input>
that has a list
attribute. The <input>
is associated to the <datalist>
via the <input>
‘s list
attribute and the id
of the <datalist>
.
From the code provided, the following form is rendered:
And when field is selected:
While <select>
and <datalist>
share some similarities, there are some major differences. In the associated <input>
element, users can type in the input field to search for a particular option. If none of the <option>
s match, the user can still use what they typed in. When the form is submitted, the value of the <input>
‘s name
and the value
of the option selected, or what the user typed in, is sent as a pair.
|
body { |
|
console.log = () => {} |
In this lesson we went over:
- The purpose of a
<form>
is to allow users to input information and send it. - The
<form>
‘saction
attribute determines where the form’s information goes. - The
<form>
‘smethod
attribute determines how the information is sent and processed. - To add fields for users to input information we use the
<input>
element and set thetype
attribute to a field of our choosing:- Setting
type
to"text"
creates a single row field for text input. - Setting
type
to"password"
creates a single row field that censors text input. - Setting
type
to"number"
creates a single row field for number input. - Setting
type
to"range"
creates a slider to select from a range of numbers. - Setting
type
to"checkbox"
creates a single checkbox that can be paired with other checkboxes. - Setting
type
to"radio"
creates a radio button that can be paired with other radio buttons. - Setting
type
to"text"
and adding thelist
attribute will pair the<input>
with a<datalist>
element if thelist
of<input>
and theid
of<datalist>
are the same. - Setting
type
to"submit"
creates a submit button.
- Setting
- A
<select>
element is populated with<option>
elements and renders a dropdown list selection. - A
<datalist>
element is populated with<option>
elements and works with an<input>
to search through choices. - A
<textarea>
element is a text input field that has a customizable area. - When a
<form>
is submitted, thename
of the fields that accept input and thevalue
of those fields are sent asname=value
pairs.
Form Validation
Let’s quickly recap:
- Client-side validations happen in the browser before information is sent to a server.
- Adding the
required
attribute to an input related element will validate that the input field has information in it. - Assigning a value to the
min
attribute of a number input element will validate an acceptable minimum value. - Assigning a value to the
max
attribute of a number input element will validate an acceptable maximum value. - Assigning a value to the
minlength
attribute of a text input element will validate an acceptable minimum number of characters. - Assigning a value to the
maxlength
attribute of a text input element will validate an acceptable maximum number of characters. - Assigning a regex to
pattern
matches the input to the provided regex. - If validations on a
<form>
do not pass, the user gets a message explaining why and the<form>
cannot be submitted.
<!-- index.html --> |
|
body { |
const message = document.getElementById('message'); |
console.log = () => {} |
Introduction to Semantic HTML
When building web pages, we use a combination of non-semantic HTML and Semantic HTML. The word semantic means “relating to meaning,” so semantic elements provide information about the content between the opening and closing tags.
By using Semantic HTML, we select HTML elements based on their meaning, not on how they are presented. Elements such as <div>
and <span>
are not semantic elements since they provide no context as to what is inside of those tags.
For example, instead of using a <div>
element to contain our header information, we could use a <header>
element, which is used as a heading section. By using a <header>
tag instead of a <div>
, we provide context as to what information is inside of the opening and closing tag.
Why use Semantic HTML?
- Accessibility: Semantic HTML makes webpages accessible for mobile devices and for people with disabilities as well. This is because screen readers and browsers are able to interpret the code better.
- SEO: It improves the website SEO, or Search Engine Optimization, which is the process of increasing the number of people that visit your webpage. With better SEO, search engines are better able to identify the content of your website and weight the most important content appropriately.
- Easy to Understand: Semantic HTML also makes the website’s source code easier to read for other web developers.
To better understand this, you can think of comparing non-semantic HTML to going into a store with no signs on the aisles. Since the aisles aren’t labeled, you don’t know what products are in those aisles. However, stores that do have signs for each aisle make it a lot easier to find the items you need, just like Semantic HTML.
Main and Footer
4 min
Two more structural elements are <main>
and <footer>
. These elements along with <nav>
and <header>
help describe where an element is located based on conventional web development standards.
The element <main>
(Represents the primary content within the body element of the web page.)
is used to encapsulate the dominant content within a webpage. This tag is separate from the <footer>
(Represents a part of a page which is meant to be at the end of a completed block of content. Common uses include copyright information for the page or additional links to relevant pages.)
and the <nav>
of a web page since these elements don’t contain the principal content. By using <main>
as opposed to a <div>
element, screen readers and web browsers are better able to identify that whatever is inside of the tag is the bulk of the content.
So how does <main>
look when incorporated into our code? That’s a great question.
<main> |
As we see above, <main>
contains an <article>
and <header>
tag with child elements that hold the most important information related to the page.
The content at the bottom of the subject information is known as the footer, indicated by the <footer>
(Represents a part of a page which is meant to be at the end of a completed block of content. Common uses include copyright information for the page or additional links to relevant pages.) element. The footer contains information such as:
- Contact information
- Copyright information
- Terms of use
- Site Map
- Reference to top of page links
For example:
<footer> |
In the example above, the footer is used to contain contact information. The <footer>
tag is separate from the <main>
element and typically located at the bottom of the content.
|
Let’s review some of the topics we covered throughout the lesson:
- Semantic HTML introduces meaning to a page through specific elements that provide context as to what is in between the tags.
- Semantic HTML is a modern standard and makes a website accessible for people who use screen readers to translate the webpage and improves your website’s SEO.
<header>
,<nav>
,<main>
and<footer>
create the basic structure of the webpage.<section>
defines elements in a document, such as chapters, headings, or any other area of the document with the same theme.<article>
holds content that makes sense on its own such as articles, blogs, comments, etc.<aside>
contains information that is related to the main content, but not required in order to understand the dominant information.<figure>
encapsulates all types of media.<figcaption>
is used to describe the media in<figure>
.<video>
,<embed>
, and<audio>
elements are used for media files.
|
CSS
References
Want to quickly review some of the concepts you’ve been learning? Take a look at this material’s cheatsheet!
Setup and Syntax
Understanding that a declaration is used to style a selected element is key to learning how to style HTML documents with CSS! The terms below explain each of the labels in the diagram:
Ruleset Terms:
- Selector—The beginning of the ruleset used to target the element that will be styled.
- Declaration Block—The code in-between (and including) the curly braces (
{ }
) that contains the CSS declaration(s). - Declaration—The group name for a property and value pair that applies a style to the selected element.
- Property—The first part of the declaration that signifies what visual characteristic of the element is to be modified.
- Value—The second part of the declaration that signifies the value of the property.
Inline Style Terms:
Opening Tag
—The start of an HTML element. This is the element that will be styled.
Attribute
—The style attribute is used to add CSS inline styles to an HTML element.
Declaration—The group name for a property and value pair that applies a style to the selected element.
Property—The first part of the declaration that signifies what visual characteristic of the element is to be modified.
Value—The second part of the declaration that signifies the value of the property.
<p style='color: red;'>I'm learning to code!</p>
I'm learning to code!
If you’d like to add more than one style with inline styles, simply keep adding to the style
attribute. Make sure to end the styles with a semicolon (;
).
<p style='color: red; font-size: 20px;'>I'm learning to code!</p>
I'm learning to code!
HTML allows you to write CSS code in its own dedicated section with a <style>
element nested inside of the <head>
element. The CSS code inside the <style>
element is often referred to as an internal stylesheet.
To create an internal stylesheet, a <style>
element must be placed inside of the <head>
element.
<head> |
After adding opening and closing <style>
tags in the head section, you can begin writing CSS code.
<head> |
Let’s review what you learned so far:
- The basic anatomy of CSS syntax written for both inline styles and stylesheets.
- Some commonly used CSS terms, such as ruleset, selector, and declaration.
- CSS inline styles can be written inside the opening HTML tag using the
style
attribute. - Inline styles can be used to style HTML, but it is not the best practice.
- An internal stylesheet is written using the
<style>
element inside the<head>
element of an HTML file. - Internal stylesheets can be used to style HTML but are also not best practice.
- An external stylesheet separates CSS code from HTML, by using the
.css
file extension. - External stylesheets are the best approach when it comes to using HTML and CSS.
- External stylesheets are linked to HTML using the
<link>
element.
Selectors
A selector is used to target the specific HTML element(s) to be styled by the declaration. One selector you may already be familiar with is the type selector. Just like its name suggests, the type selector matches the type of the element in the HTML document.
In the previous lesson, you changed the color of a paragraph element.
p { |
This is an instance of using the type selector! The element type is p
, which comes from the HTML <p>
element.
Some important notes on the type selector:
- The type selector does not include the angle brackets.
- Since element types are often referred to by their opening tag name, the type selector is sometimes referred to as the tag name or element selector.
You learned how the type selector selects all elements of a given type. Well, the universal selector selects all elements of any type.Targeting all of the elements on the page has a few specific use cases, such as resetting default browser styling or selecting all children of a parent element.
The universal selector uses the *
character in the same place where you specified the type selector in a ruleset, like so:
* { |
<p class='brand'>Sole Shoe Company</p> |
The paragraph element in the example above has a class
attribute within the opening tag of the<p>
element. The class
attribute is set to 'brand'
. To select this element using CSS, we can create a ruleset with a class selector of .brand
.
.brand { |
To select an HTML element by its class using CSS, a period (.
) must be prepended to the class’s name. In the example above, the class is brand
, so the CSS selector for it is .brand
.
For instance, perhaps there’s a heading element that needs to be green and bold. You could write two CSS rulesets like so:
.green { |
Then, you could include both of these classes on one HTML element like this:
<h1 class='green bold'> ... </h1> |
We can add multiple classes to an HTML element’s class
attribute by separating them with a space. This enables us to mix and match CSS classes to create many unique styles without writing a custom class for every style combination needed.
Oftentimes it’s important to select a single element with CSS to give it its own unique style. If an HTML element needs to be styled uniquely, we can give it an ID using the id
attribute.
<h1 id='large-title'> ... </h1> |
In contrast to class
which accepts multiple values, and can be used broadly throughout an HTML document, an element’s id
can only have a single value, and only be used once per page.
To select an element’s ID with CSS, we prepend the id
name with a number sign (#
). For instance, if we wanted to select the HTML element in the example above, it would look like this:
#large-title { |
The id
name is large-title
, therefore the CSS selector for it is #large-title
.
The attribute selector can be used to target HTML elements that already contain attributes. Elements of the same type can be targeted differently by their attribute or attribute value. This alleviates the need to add new code, like the class
or id
attributes.
Attributes can be selected similarly to types, classes, and IDs.
[href]{ |
The most basic syntax is an attribute surrounded by square brackets. In the above example: [href]
would target all elements with an href
attribute and set the color
to magenta
.
And it can get more granular from there by adding type and/or attribute values. One way is by using type[attribute*=value]
. In short, this code selects an element where the attribute contains any instance of the specified value. Let’s take a look at an example.
<img src='/images/seasons/cold/winter.jpg'> |
The HTML code above renders two <img>
elements, each containing a src
attribute with a value equaling a link to an image file.
img[src*='winter'] { |
Now take a look at the above CSS code. The attribute selector is used to target each image individually.
The first ruleset looks for an
<img>
element with an attribute of<src>
that contains the stringwinter
and sets the
height
to50px
.The second ruleset looks for an
img
element with an attribute ofsrc
that contains the string'summer'
, and sets theheight
to100px
.
Notice how no new HTML markup (like a class or id) needed to be added, and we were still able to modify the styles of each image independently. This is one advantage to using the attribute selector!
Pseudo-class
5 min
You may have observed how the appearance of certain elements can change, or be in a different state, after certain user interactions. For instance:
- When you click on an
<input>
element, and a blue border is added showing that it is in focus. - When you click on a blue
<a>
link to visit to another page, but when you return the link’s text is purple. - When you’re filling out a form and the submit button is grayed out and disabled. But when all of the fields have been filled out, the button has color showing that it’s active.
These are all examples of pseudo-class selectors in action! In fact, :focus
, :visited
, :disabled
, and :active
are all pseudo-classes. Factors such as user interaction, site navigation, and position in the document tree can all give elements a different state with pseudo-class.
A pseudo-class can be attached to any selector. It is always written as a colon :
followed by a name. For example p:hover
.
p:hover { |
In the above code, whenever the mouse hovers over a paragraph element, that paragraph will have a lime-colored background.
Classes and IDs
10 min
CSS can select HTML elements by their type, class, and ID. CSS classes and IDs have different purposes, which can affect which one you use to style HTML elements.
CSS classes are meant to be reused over many elements. By writing CSS classes, you can style elements in a variety of ways by mixing classes. For instance, imagine a page with two headlines. One headline needs to be bold and blue, and the other needs to be bold and green. Instead of writing separate CSS rules for each headline that repeat each other’s code, it’s better to write a .bold
CSS rule, a .green
CSS rule, and a .blue
CSS rule. Then you can give one headline the bold green
classes, and the other the bold blue
classes.
While classes are meant to be used many times, an ID is meant to style only one element. As you’ll learn in the next exercise, IDs override the styles of types and classes. Since IDs override these styles, they should be used sparingly and only on elements that need to always appear the same.
Specificity
7 min
Specificity is the order by which the browser decides which CSS styles will be displayed. A best practice in CSS is to style elements while using the lowest degree of specificity so that if an element needs a new style, it is easy to override.
IDs are the most specific selector in CSS, followed by classes, and finally, type. For example, consider the following HTML and CSS:
<h1 class='headline'>Breaking News</h1> |
In the example code above, the color of the heading would be set to firebrick
, as the class selector is more specific than the type selector. If an ID attribute (and selector) were added to the code above, the styles within the ID selector’s body would override all other styles for the heading.
Over time, as files grow with code, many elements may have IDs, which can make CSS difficult to edit since a new, more specific style must be created to change the style of an element.
To make styles easy to edit, it’s best to style with a type selector, if possible. If not, add a class selector. If that is not specific enough, then consider using an ID selector.
Chaining
4 min
When writing CSS rules, it’s possible to require an HTML element to have two or more CSS selectors at the same time.
This is done by combining multiple selectors, which we will refer to as chaining. For instance, if there was a special
class for <h1>
elements, the CSS would look like below:
h1.special { |
The code above would select only the <h1>
elements with a class of special
. If a <p>
element also had a class of special
, the rule in the example would not style the paragraph.
Descendant Combinator
7 min
In addition to chaining selectors to select elements, CSS also supports selecting elements that are nested within other HTML elements, also known as descendants. For instance, consider the following HTML:
<ul class='main-list'> |
The nested <li>
elements are descendants of the <ul>
element and can be selected with the descendant combinator like so:
.main-list li { |
In the example above, .main-list
selects the element with the.main-list
class (the <ul>
element). The descendant <li>
‘s are selected by adding li
to the selector, separated by a space. This results in .main-list li
as the final selector.
Selecting elements in this way can make our selectors even more specific by making sure they appear in the context we expect.
Chaining and Specificity
5 min
In the last exercise, instead of selecting all <h5>
elements, you selected only the <h5>
elements nested inside the .description
elements. This CSS selector was more specific than writing only h5
. Adding more than one tag, class, or ID to a CSS selector increases the specificity of the CSS selector.
For instance, consider the following CSS:
p { |
Both of these CSS rules define what a <p>
element should look like. Since .main p
has a class and a p
type as its selector, only the <p>
elements inside the .main
element will appear red
. This occurs despite there being another more general rule that states <p>
elements should be blue
.
Multiple Selectors
2 min
In order to make CSS more concise, it’s possible to add CSS styles to multiple CSS selectors all at once. This prevents writing repetitive code.
For instance, the following code has repetitive style attributes:
h1 { |
Instead of writing font-family: Georgia
twice for two selectors, we can separate the selectors by a comma to apply the same style to both, like this:
h1, |
By separating the CSS selectors with a comma, both the <h1>
elements and the elements with the menu
class will receive the font-family: Georgia
styling.
Review
Let’s review what you learned:
- CSS can select HTML elements by type, class, ID, and attribute.
- All elements can be selected using the universal selector.
- An element can have different states using the pseudo-class selector.
- Multiple CSS classes can be applied to one HTML element.
- Classes can be reusable, while IDs can only be used once.
- IDs are more specific than classes, and classes are more specific than type. That means IDs will override any styles from a class, and classes will override any styles from a type selector.
- Multiple selectors can be chained together to select an element. This raises the specificity but can be necessary.
- Nested elements can be selected by separating selectors with a space.
- Multiple unrelated selectors can receive the same styles by separating the selector names with commas.
Fundamental CSS Visual Rules
Font Family
6 min
If you’ve ever used word processing software, like Microsoft Word or Google Docs, chances are that you probably also used a feature that allowed you to change the font you were typing in. Font refers to the technical term typeface, or font family.
To change the typeface of text on your web page, you can use the font-family
property.
h1 { |
In the example above, the font family for all main heading elements has been set to Garamond
.
When setting typefaces on a web page, keep the following points in mind:
- The font specified must be installed on the user’s computer or downloaded with the site.
- Web safe fonts are a group of fonts supported across most browsers and operating systems.
- Unless you are using web safe fonts, the font you choose may not appear the same between all browsers and operating systems.
- When the name of a typeface consists of more than one word, it’s a best practice to enclose the typeface’s name in quotes, like so:
h1 { |
Font Size
1 min
Changing the typeface isn’t the only way to customize the text. Oftentimes, different sections of a web page are highlighted by modifying the font size.
To change the size of text on your web page, you can use the font-size
property.
p { |
In the example above, the font-size
of all paragraphs was set to 18px
. px
means pixels, which is one way to measure font size.
Font Weight
1 min
In CSS, the font-weight
property controls how bold or thin text appears.
p { |
In the example above, all paragraphs on the web page would appear bolded.
The font-weight
property has another value: normal
. Why does it exist?
If we wanted all text on a web page to appear bolded, we could select all text elements and change their font weight to bold
. If a certain section of text was required to appear normal, however, we could set the font weight of that particular element to normal
, essentially shutting off bold for that element.
Text Align
2 min
No matter how much styling is applied to text (typeface, size, weight, etc.), the text always appears on the left side of the container in which it resides.
To align text we can use the text-align
property. The text-align
property will align text to the element that holds it, otherwise known as its parent.
h1 { |
The text-align
property can be set to one of the following commonly used values:
left
— aligns text to the left side of its parent element, which in this case is the browser.center
— centers text inside of its parent element.right
— aligns text to the right side of its parent element.justify
— spaces out text in order to align with the right and left side of the parent element.
Color and Background Color
3 min
Before discussing the specifics of color, it’s important to make two distinctions about color. Color can affect the following design aspects:
- Foreground color
- Background color
Foreground color is the color that an element appears in. For example, when a heading is styled to appear green, the foreground color of the heading has been styled. Conversely, when a heading is styled so that its background appears yellow, the background color of the heading has been styled.
In CSS, these two design aspects can be styled with the following two properties:
color
: this property styles an element’s foreground color.background-color
: this property styles an element’s background color.
h1 { |
In the example above, the text of the heading will appear in red, and the background of the heading will appear blue.
Opacity
2 min
Opacity is the measure of how transparent an element is. It’s measured from 0 to 1, with 1 representing 100%, or fully visible and opaque, and 0 representing 0%, or fully invisible.
Opacity can be used to make elements fade into others for a nice overlay effect. To adjust the opacity of an element, the syntax looks like this:
.overlay { |
In the example above, the .overlay
element would be 50% visible, letting whatever is positioned behind it show through.
Background Image
3 min
CSS has the ability to change the background of an element. One option is to make the background of an element an image. This is done through the CSS property background-image
. Its syntax looks like this:
.main-banner { |
- The
background-image
property will set the element’s background to display an image. - The value provided to
background-image
is aurl
. Theurl
should be a URL to an image. Theurl
can be a file within your project, or it can be a link to an external site. To link to an image inside an existing project, you must provide a relative file path. If there was an image folder in the project, with an image namedmountains.jpg
, the relative file path would look like below:
.main-banner { |
Important
3 min
!important
can be applied to specific declarations, instead of full rules. It will override any style no matter how specific it is. As a result, it should almost never be used. Once !important
is used, it is very hard to override.
The syntax of !important
in CSS looks like this:
p { |
Since !important
is used on the p
selector’s color
attribute, all p
elements will appear blue
, even though there is a more specific .main p
selector that sets the color
attribute to red
.
One justification for using !important
is when working with multiple stylesheets. For example, if we are using the Bootstrap CSS framework and want to override the styles for one specific HTML element, we can use the !important
property.
Box Model
Introduction to the Box Model
2 min
Browsers load HTML elements with default position values. This often leads to an unexpected and unwanted user experience while limiting the views you can create. In this lesson, you will learn about the box model, an important concept to understand how elements are positioned and displayed on a website.
If you have used HTML and CSS, you have unknowingly seen aspects of the box model[^1]. For example, if you have set the background color of an element, you may have noticed that the color was applied not only to the area directly behind the element but also to the area to the right of the element. Also, if you have aligned text, you know it is aligned relative to something. What is that something?
All elements on a web page are interpreted by the browser as “living” inside of a box. This is what is meant by the box model.
For example, when you change the background color of an element, you change the background color of its entire box.
In this lesson, you’ll learn about the following aspects of the box model:
- The dimensions(weight and height) of an element’s box.
- The borders [^2]of an element’s box.
- The paddings of an element’s box.
- The margins of an element’s box.
Let’s begin!
[^1]:The Box Model is a CSS layout mechanism that the web browser uses to render content organized by box-shaped elements. Each element is made of four specific areas: - width and height: The width and height of the content area. - padding: The amount of space between the content area and the border. - border: The thickness and style of the border surrounding the content area and padding. - margin: The amount of space between the border and the outside edge of the element. CSS Box Model Diagram This area contains the actual content of an element, including text and images. It also sometimes has a background-color or background-image.
[^2]:Defines decorative lines around HTML elements to create visual separation and emphasis.
The Box Model is a CSS layout mechanism that the web browser uses to render content organized by box-shaped elements. Each element is made of four specific areas:
width
andheight
: The width and height of the content area.padding
: The amount of space between the content area and the border.border
: The thickness and style of the border surrounding the content area and padding.margin
: The amount of space between the border and the outside edge of the element.
Height and Width
p { |
In this example, the height
and width
of paragraph elements are set to 80 pixels and 240 pixels, respectively — the px
in the code above stands for pixels.
Pixels allow you to set the exact size of an element’s box (width and height). When the width and height of an element are set in pixels, it will be the same size on all devices — an element that fills a laptop screen will overflow[^3] a mobile screen.
[^3]:Defines how a block level element should handle content that goes beyond its boundaries.
Borders
6 min
A border is a line that surrounds an element, like a frame around a painting. Borders can be set with a specific width
, style
, and color
:
width
—The thickness of the border. A border’s thickness can be set in pixels or with one of the following keywords:thin
,medium
, orthick
.style
—The design of the border. Web browsers can render any of 10 different styles. Some of these styles include:none
,dotted
, andsolid
.color
—The color of the border. Web browsers can render colors using a few different formats, including 140 built-in color keywords.
p { |
In the example above, the border has a width of 3 pixels, a style of solid
, and a color of coral
. All three properties are set in one line of code.
The default border is medium none color
, where color
is the current color of the element. If width
, style
, or color
are not set in the CSS file, the web browser assigns the default value for that property.
p.content-header { |
In this example, the border style is set to solid
and the color is set to coral
. The width is not set, so it defaults to medium
.
Border Radius
3 min
Ever since we revealed the borders of boxes, you may have noticed that the borders highlight the true shape of an element’s box: square. Thanks to CSS, a border doesn’t have to be square.
You can modify the corners of an element’s border box with the border-radius
property.
div.container { |
The code in the example above will set all four corners of the border to a radius of 5 pixels (i.e. the same curvature that a circle with a radius of 5 pixels would have).
You can create a border that is a perfect circle by first creating an element with the same width and height, and then setting the radius equal to half the width of the box, which is 50%.
div.container { |
The code in the example above creates a <div>
that is a perfect circle.
Padding
6 min
The space between the contents of a box and the borders of a box is known as padding. Padding is like the space between a picture and the frame surrounding it. In CSS, you can modify this space with the padding
property.
p.content-header { |
The code in this example puts 10 pixels of space between the content of the paragraph (the text) and the borders, on all four sides.
The padding
property is often used to expand the background color and make the content look less cramped.
If you want to be more specific about the amount of padding on each side of a box’s content, you can use the following properties:
- Preview: Docs Defines the width of the top padding for an element.
padding-top
- Preview: Docs Defines the width of the right padding for an element.
padding-right
- Preview: Docs Loading link description
padding-bottom
- Preview: Docs Defines the width of the left padding for an element.
padding-left
Each property affects the padding on only one side of the box’s content, giving you more flexibility in customization.
p.content-header { |
In the example above, only the bottom side of the paragraph’s content will have a padding
of 10 pixels.
Padding Shorthand
5 min
Another implementation of the padding
property lets you specify exactly how much padding there should be on each side of the content in a single declaration. A declaration that uses multiple properties as values is known as a shorthand property.
Padding shorthand lets you specify all of the padding
properties as values on a single line:
- Preview: Docs Loading link description
padding-top
- Preview: Docs Loading link description
padding-right
- Preview: Docs Loading link description
padding-bottom
- Preview: Docs Loading link description
padding-left
You can specify these properties in a few different ways:
4 Values
p.content-header { |
In the example above, the four values 6px 11px 4px 9px
correspond to the amount of padding on each side, in a clockwise rotation. In order, it specifies the padding-top value (6px
), the padding-right value (11px
), the padding-bottom value (4px
), and the padding-left value (9px
) of the content.
3 Values
p.content-header { |
If the left and right sides of the content can be equal, the padding shorthand property allows for 3 values to be specified. The first value sets the padding-top value (5px
), the second value sets the padding-left and padding-right values (10px
), and the third value sets the padding-bottom value (20px
).
2 Values
p.content-header { |
And finally, if the top and bottom sides can be equal, and the left and right sides can be equal, you can specify 2 values. The first value sets the padding-top and padding-bottom values (5px
), and the second value sets the padding-left and padding-right values (10px
).
Margin
4 min
So far you’ve learned about the following components of the box model: content, borders and padding. The fourth and final component of the box modelis margin.
Margin refers to the space directly outside of the box. The margin
property is used to specify the size of this space.
p { |
The code in the example above will place 20 pixels of space on the outside of the paragraph’s box on all four sides. This means that other HTML elements on the page cannot come within 20 pixels of the paragraph’s border.If you want to be even more specific about the amount of margin on each side of a box, you can use the following properties:
- Preview: Docs Loading link description
margin-top
- Preview: Docs Loading link description
margin-right
- Preview: Docs Loading link description
margin-bottom
- Preview: Docs Defines the left margin area for an element.
margin-left
Each property affects the margin on only one side of the box, providing more flexibility in customization.
p { |
In the example above, only the right side of the paragraph’s box will have a margin of 15 pixels. It’s common to see margin values used for a specific side of an element.
Margin Shorthand
1 min
What if you don’t want equal margins on all four sides of the box and don’t have time to separate properties for each side? You’re in luck! Margin can be written as a shorthand property as well. The shorthand syntax for margins is the same as padding, so if you’re feeling comfortable with that, skip to the instructions. Otherwise, read on to learn how to use margin shorthand!
Similar to padding shorthand, margin shorthand lets you specify all of the margin
properties as values on a single line:
- Preview: Docs Loading link description
margin-top
- Preview: Docs Loading link description
margin-right
- Preview: Docs Defines the bottom margin area for an element.
margin-bottom
- Preview: Docs Loading link description
margin-left
You can specify these properties in a few different ways:
4 Values
p { |
In the example above, the four values 6px 10px 5px 12px
correspond to the thickness of the margin on each side, in a clockwise rotation. In order, it specifies the margin-top value (6px
), the margin-right value (10px
), the margin-bottom value (5px
), and the margin-left value (12px
) of the content.
3 Values
p { |
If the left and right sides of the content can be equal, the margin shorthand property allows for 3 values to be specified. The first value sets the margin-top value (5px
), the second value sets the margin-left and margin-right values (12px
), and the third value sets the margin-bottom value (4px
).
2 Values
p { |
And finally, if the top and bottom sides can be equal, and the left and right sides can be equal, you can specify 2 values. The first value sets the margin-top and margin-bottom values (20px
), and the second value sets the margin-left and margin-right values (10px
).
Margin Collapse

3 min
As you have seen, padding is space added inside an element’s border, while margin is space added outside an element’s border. One additional difference is that top and bottom margins, also called vertical margins, collapse, while top and bottom padding does not.
Horizontal margins (left and right), like padding, are always displayed and added together. For example, if two divs with ids #div-one
and #div-two
, are next to each other, they will be as far apart as the sum of their adjacent margins.
#img-one { |
In this example, the space between the #img-one
and #img-two
borders is 40 pixels. The right margin of #img-one
(20px
) and the left margin of #img-two
(20px
) add to make a total margin of 40 pixels.
Unlike horizontal margins, vertical margins do not add. Instead, the larger of the two vertical margins sets the distance between adjacent elements.
#img-one { |
In this example, the vertical margin between the #img-one
and #img-two
elements is 30 pixels. Although the sum of the margins is 50 pixels, the margin collapses so the spacing is only dependent on the #img-one
bottom margin.
It may be helpful to think of collapsing vertical margins as a short person trying to push a taller person. The tall person has longer arms and can easily push the short person, while the person with short arms cannot reach the person with long arms.
Minimum and Maximum Height and Width
5 min
Because a web page can be viewed through displays of differing screen size, the content on the web page can suffer from those changes in size. To avoid this problem, CSS offers two properties that can limit how narrow or how wide an element’s box can be sized to:
min-width
—this property ensures a minimum width of an element’s box.max-width
—this property ensures a maximum width of an element’s box.
p { |
In the example above, the width of all paragraphs will not shrink below 300 pixels, nor will the width exceed 600 pixels.
Content, like text, can become difficult to read when a browser window is narrowed or expanded. These two properties ensure that content is legible by limiting the minimum and maximum widths of an element.
You can also limit the minimum and maximum height of an element:
min-height
— this property ensures a minimum height for an element’s box.max-height
— this property ensures a maximum height of an element’s box.
p { |
In the example above, the height of all paragraphs will not shrink below 150 pixels and the height will not exceed 300 pixels.
What will happen to the contents of an element’s box if the max-height
property is set too low? It’s possible for the content to spill outside of the box, resulting in content that is not legible. You’ll learn how to work around this issue in the next exercise.
Overflow
5 min
All of the components of the box model comprise an element’s size. For example, an image that has the following dimensions is 364 pixels wide and 244 pixels tall.
- 300 pixels wide
- 200 pixels tall
- 10 pixels padding on the left and right
- 10 pixels padding on the top and bottom
- 2 pixels border on the left and right
- 2 pixels border on the top and bottom
- 20 pixels margin on the left and right
- 10 pixels margin on the top and bottom
The total dimensions (364px by 244px) are calculated by adding all of the vertical dimensions together and all of the horizontal dimensions together. Sometimes, these components result in an element that is larger than the parent’s containing area.
How can we ensure that we can view all of an element that is larger than its parent’s containing area?
The overflow
property controls what happens to content that spills, or overflows, outside its box. The most commonly used values are:
hidden
—when set to this value, any content that overflows will be hidden from view.scroll
—when set to this value, a scrollbar will be added to the element’s box so that the rest of the content can be viewed by scrolling.visible
—when set to this value, the overflow content will be displayed outside of the containing element. Note, this is the default value.
p { |
In the example above, if any of the paragraph content overflows (perhaps a user resizes their browser window), a scrollbar will appear so that users can view the rest of the content.
The overflow property is set on a parent element to instruct a web browser on how to render child elements. For example, if a div’s overflow property is set to scroll
, all children of this div will display overflowing content with a scroll bar.
For a more in-depth look at overflow
, including additional properties like overflow-x
and overflow-y
that separate out the horizontal and vertical values, head over to the MDN documentation.
Visibility
3 min
Elements can be hidden from view with the visibility
property.
The visibility
property can be set to one of the following values:
hidden
— hides an element.visible
— displays an element.collapse
— collapses an element.
<ul> |
In the example above, the list item with a class of future
will be hidden from view in the browser.
Keep in mind, however, that users can still view the contents of the list item (e.g., Donate
) by viewing the source code in their browser. Furthermore, the web page will only hide the contents of the element. It will still leave an empty space where the element is intended to display.
Note: What’s the difference between display: none
and visibility: hidden
? An element with display: none
will be completely removed from the web page. An element with visibility: hidden
, however, will not be visible on the web page, but the space reserved for it will.
Review
Let’s take a minute to review what you learned:
- The box model comprises a set of properties used to create space around and between HTML elements.
- The height and width of a content area can be set in pixels or percentages.
- Borders surround the content area and padding of an element. The color, style, and thickness of a border can be set with CSS properties.
- Padding is the space between the content area and the border. It can be set in pixels or percent.
- Margin is the amount of spacing outside of an element’s border.
- Horizontal margins add, so the total space between the borders of adjacent elements is equal to the sum of the right margin of one element and the left margin of the adjacent element.
- Vertical margins collapse, so the space between vertically adjacent elements is equal to the larger margin.
margin: 0 auto
horizontally centers an element inside of its parent content area, if it has a width.- The
overflow
property can be set todisplay
, hidden, or scroll, and dictates how HTML will render content that overflows its parent’s content area. - The
visibility
property can hide or show elements.
Changing the Box Model
The last lesson focused on the most important aspects of the box model: box dimensions,boders,padding,and margin.
The box model however, has an awkward limitation regarding box dimensions. This limitation is best illustrated with an example.
<h1>Hello World</h1> |
In the example above, a heading element’s box has solid, black, 1 pixel thick borders. The height of the box is 200 pixels, while the width of the box is 300 pixels. A padding of 10 pixels has also been set on all four sides of the box’s content.
Unfortunately, under the current box model, the border thickness and the padding will affect the dimensions of the box.
The 10 pixels of padding increases the height of the box to 220 pixels and the width to 320 pixels. Next, the 1-pixel thick border increases the height to 222 pixels and the width to 322 pixels.
Under this box model, the border thickness and padding are added to the overall dimensions of the box. This makes it difficult to accurately size a box. Over time, this can also make all of a web page’s content difficult to position and manage.
In this brief lesson, you’ll learn how to use a different technique that avoids this problem altogether.
Box Model: Content-Box

1 min
Many properties in CSS have a default value and don’t have to be explicitly set in the stylesheet.
For example, the default font-weight
of text is normal
, but this property-value pair is not typically specified in a stylesheet.
The same can be said about the box model that browsers assume. In CSS, the box-sizing
property controls the type of box model the browser should use when interpreting a web page.
The default value of this property is content-box
. This is the same box model that is affected by border thickness and padding.
Box Model: Border-Box
2 min
Fortunately, we can reset the entire box model and specify a new one: border-box
.
* { |
The code in the example above resets the box model to border-box
for all HTML elements. This new box model avoids the dimensional issues that exist in the former box model you learned about.
In this box model, the height and width of the box will remain fixed. The border thickness and padding
will be included inside of the box, which means the overall dimensions of the box do not change.
<h1>Hello World</h1> |
In the example above, the height of the box would remain at 150 pixels and the width would remain at 200 pixels. The border thickness and padding would remain entirely inside of the box.
Review: Changing the Box Model
Let’s review what you learned:
- In the default box model, box dimensions are affected by border thickness and padding.
- The
box-sizing
property controls the box model used by the browser. - The default value of the
box-sizing
property iscontent-box
. - The value for the new box model is
border-box
. - The
border-box
model is not affected by border thickness or padding.
Display and Positioning
Flow of HTML
1 min
A browser will render the elements of an HTML document that has no CSS from left to right, top to bottom, in the same order as they exist in the document. This is called the flow of elements in HTML.
In addition to the properties that it provides to style HTML elements, CSS includes properties that change how a browser positions elements. These properties specify where an element is located on a page, if the element can share lines with other elements, and other related attributes.
In this lesson, you will learn five properties for adjusting the position of HTML elements in the browser:
- position
- display
- z-index
- float
- clear
Each of these properties will allow us to position and view elements on a web page. They can be used in conjunction with any other styling properties you may know.
Position
4 min
Take a look at the block-level elements in the image below:
Block-level elements like these boxes create a block the full width of their parent elements, and they prevent other elements from appearing in the same horizontal space.
Notice the block-level elements in the image above take up their own line of space and therefore don’t overlap each other. In the browser to the right, you can see block-level elements also consistently appear on the left side of the browser. This is the default position for block-level elements.
The default position of an element can be changed by setting its position
property. The position
property can take one of five values:
In the next few exercises, you’ll learn about the values in the list above. For now, it’s important to understand that if you favor the default position of an HTML element, you don’t need to set its position
property.