Lecture 1
Welcome to EN.601.280
Full-Stack JavaScript!
A full-stack JavaScript developer is a person who can build modern software applications using primarily the JavaScript programming language. Creating a modern software application involves integrating many technologies - from creating the user interface to saving information in a database and everything else in between and beyond.
A full-stack developer is not an expert in everything. Rather, s/he is someone who is familiar with various (software application) frameworks and the ability to take a concept and turn it into a finished product.
This course is designed to provide a solid introduction to the JavaScript language. In particular, we will explore the features of JavaScript (such as asynchronous programming) that are not familiar to many students who are introduced to programming with languages such as Java, C++ or python.
After exploring the core programming concepts, the class lectures and homework assignments will introduce how JavaScript is used as a popular technology for software development. In particular, we will explore Web development with the MERN stack (MongoDB with Mongoose.js, Express.js, React, Node.js).
In the process, you will also learn about the engineering of modern software applications, emphasizing: object-oriented design, decomposition, encapsulation, abstraction, testing, and good programming style.
Instructional Approach
When it comes to learning a new programming languages for those who already know programming, there are two general type of audience: those who prefer to learn by doing, and those who prefer learning concepts from the ground up. This course is designed to serve both groups.
We alternate between step-by-step tutorial lessons where we learn by doing (building applications), and concept-focused lessons where we dissect a part of the language and learn all there is to learn about it.
For instance, in this lecture we will build a very simple web app (learn by doing). In the next lecture, we will learn about JavaScript basics (how to declare variables, what are the data types, ...).
JavaScript History
- Created in 1995 by Brendan Eich as LiveScript to enhance web pages in Netscape 2.0
- Renamed to JavaScript as a marketing ploy to capitalize on Java's popularity (despite the two had very little in common).
- Standardized as ECMAScript since 1997.
- ECMAScript 6 (2015) introduced a great many useful addition (Object-Oriented support, Modules, Strict mode, ...)
- Old JavaScript: Some good ideas, lots of cruft.
- Modern JavaScript (ECMAScript 6 and beyond): Good ideas alive and kicking, cruft (is gone/can be avoided).
- Today, it is one of the most popular programming languages. (E.g, see StackOverflow 2020 Developer Survey, PYPL Index, IEEE Spectrum Top Programming Languages 2020)
In 2001, Paul Graham wrote1:
I would not even use JavaScript, if I were you... Most of the JavaScript I see on the Web isn't necessary, and much of it breaks.
In 2007, Jeff Atwood coined Atwood's law2:
Any application that can be written in JavaScript will eventually be written in JavaScript.
This video summaries it:
A revised version of the essay can be found at http://paulgraham.com/road.html. The original quote can be found in the book Hackers & Painters.
Why Learn JavaScript?
JavaScript was originally developed to add functionality to web pages but it's now used for much more!
- JavaScript runs on pretty much any platform from web pages, to server backends and even hardware.
- There are some great build and deployment tools and frameworks written in JavaScript that are useful in many applications.
- It's a great introduction to software construction and multi-paradigm programming concepts.
- JavaScript is easy to learn. But beware - it's hard to master!
Step 1
We will build a simple web application similar to sleepyti.me but limited to suggesting "wake up" times based on calculating sleep cycles.
- A sleep cycle lasts about 90 minutes and a good night's sleep consists of 5-6 sleep cycles.
- If you wake up in the middle of a sleep cycle, you will feel groggy even if you've completed several cycles prior to waking up.
We do this with the full knowledge that you (most likely) have never done anything like this before. There is going to be many new encounters: syntax, terminology, etc. Don't worry! You are not expected to learn it all in one tutorial. We will revisit every unfamiliar topic again and again throughout the course. In the end, you will look back and find this example an astonishingly easy one! So, buckle up for the ride, and when you face something you don't know about, take it in your stride.
Step 2
-
The browser understands Hyper Text Markup Language, or HTML.
-
Create an empty file and call it
index.html
-
Open the file in your favorite text editor!
The extension of your file must be
html
. The name,index
, is just a convention for naming the landing page of websites.
- HTML document is essentially a text file organized into sections. Each section is contained within
<tagname>...</tagname>
and is called an HTML element. Here is the minimal structure:
<html>
<head>
<!-- meta data about the page -->
</head>
<body>
<!-- content of the page -->
</body>
</html>
- Note that HTML elements can be nested.
HTML is fairly easy and you will pick it up as we progress through the course. Please see the Appendix for more information.
- Copy the following to your
index.html
<html>
<head>
<title>SleepTime App</title>
</head>
<body>
<p>Hello world!</p>
</body>
</html>
- Open
index.html
in your favorite browser.
Step 3
- Add the following to the
<body>
element.
<p>If you go to bed NOW, you should wake up at...</p>
<button>zzz</button>
- Add the response which we want to see after clicking on
zzz
button, after<button>zzz</button>
<p>It takes the average human fourteen minutes to fall asleep.</p>
<p>If you head to bed right now, you should try to wake up at one of the following times:</p>
<p>11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
<p>A good night's sleep consists of 5-6 complete sleep cycles.</p>
The wake up times are calculated for someone going to bed at 10:00 PM, and hard-coded here. We will make our app calculate these times dynamically when the
zzz
button is clicked.
Step 4
The onclick
event
-
When we click on the
zzz
button we want something to happen! -
Update the
button
tag and add the followingonclick
attribute:
<button onclick="window.alert('buzz!');">zzz</button>
HTML attributes provide additional information about HTML elements. They are always specified in the start tag, usually in name/value pairs like:
name="value"
.
- Save the
index.html
file; refresh theindex
page in the browser. Then, click on thezzz
button. You must see a pop-up alert window sayingbuzz!
The
window.alert('buzz!');
is a JavaScript statement. Thewindow
object represents an open window in a browser.
- Let's add another statement to
onclick
event of thezzz
button.
<button onclick="window.alert('buzz!');console.log('fizz!');">
-
Save the
index.html
file; refresh theindex
page in the browser. -
In your browser, open "Developer Tools" (typically, you can do this by a right click and selecting "Inspect") and find the "Console" tab.
-
Now, click on the
zzz
button. In addition to a pop-up alert window with the messagebuzz!
, you must see the messagefizz!
printed to the console.
console.log()
provides access to the browser's debugging console.
The <script>
tag
-
It will be difficult to read more than a few (JavaScript) statements for the
onclick
attribute of thezzz
button. It is not advisable to write event handlers (JavaScript statements that are executed in response to an event) using attributes of button (or other HTML) elements. The HTML document will soon become unwieldy. -
A better approach is putting all JavaScript statements (code) in a dedicated section, perhaps group the statements (pertaining to handling an event) in a function and call that function in the
onclick
event. -
Add the following section to the end of the
<body>
element (right before the closing</body>
tag):
<script>
function handleOnClickEvent() {
window.alert('buzz!');
console.log('fizz!');
}
</script>
The
<script>
element is used to include JavaScript in HTML.
- Update the
onclick
attribute of thezzz
button:
<button onclick="handleOnClickEvent();">zzz</button>
- Save the
index.html
file; refresh theindex
page in the browser. Then, click on thezzz
button; it must work as before (producing alert window and console message).
Step 5
- Let's change the presentation of content by aligning to center! Add the following
style
attribute to the<body>
tag.
<body style="text-align: center;">
- We can further change the text and background colors.
<body style="text-align: center;
color: #7FDBFF;
background-color:#001f3f;"
>
- Save the
index.html
file; refresh theindex
page in the browser. Notice the changes to the presentation of content.
#7FDBFF
and#001f3f
are hexadecimal values representing colors. I selected these by inspecting the elements on sleepyti.me website. This sort of inspection can be done using your browser's developer tools. You can also use various HTML color picker tools for such purposes.
The <style>
element
-
Suppose we write elaborate styling for a commonly used HTML element like the
<p>
element (which represents a paragraph). We many have several dozens<p>
elements. We would have to rewrite the same elaborate (lengthly) style attribute for each<p>
element. This way of writing styles can easily become unwieldy. -
A better way is to collect all the inline styles into what is called an internal Cascading Style Sheets or CSS using a
<style>
element. -
Add the following to the end of
<head>
element (right before the closing tag</head>
):
<style>
body {
text-align: center;
color: #7FDBFF;
background-color: #001f3f;
}
</style>
More styling!
-
Let's put a border around the "output" (the stuff we shall display once the
zzz
button is clicked). -
Wrap the content after
zzz
button in a<div></div>
tag:
<div>
<p>It takes the average human fourteen minutes to fall asleep.</p>
<p>If you head to bed right now, you should try to wake up at one of the following times:</p>
<p>11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
<p>A good night's sleep consists of 5-6 complete sleep cycles.</p>
</div>
HTML
<div>
tag defines a division or a section in an HTML document. You can think of it as a container for other HTML elements - which is then styled with CSS or manipulated with JavaScript.
- Now add the following to the end of
<style>
section (right before the closing tag</style>
):
div {
margin: 1em 5em 1em 5em;
border: 3px solid white;
}
-
The
border
property is descriptive; you may want to look up the CSS margin property and CSS units. -
Save the
index.html
file; refresh theindex
page in the browser.
The
<div>
is a common element. If we were to expand this web app in the future, we would likely have many morediv
elements. The above styling will be applied to alldiv
elements. It would be forward thinking to ensure the styling is applied only to thediv
that contains the "output".
- Add the following class attribute to the
<div>
element.
<div class="output">
- Update the
div
CSS selector to.output
.output {
margin: 1em 5em 1em 5em;
border: 3px solid white;
}
Classes allow CSS (and Javascript) to select and access specific elements. Note the style selector for a class starts with a dot as in
.output
.
- Save the
index.html
file; refresh theindex
page in the browser.
Step 6
-
Preferably we want the "output" to be hidden until we click on the
zzz
button. -
Hiding the output is simple; add the following
display
property to the style selector for output.
.output {
margin: 1em 5em 1em 5em;
border: 3px solid white;
display: none;
}
-
Save the
index.html
file; refresh theindex
page in the browser. -
Update the
handleOnClickEvent
function as follows:
<script>
function handleOnClickEvent() {
let output = document.querySelector('.output');
output.style.display = 'block';
}
</script>
The
document
object is the root node of the HTML document. When an HTML document is loaded into a browser, it becomes adocument
object. Thedocument
object is also called the DOM (Document Object Model).The
querySelector()
method returns the first element of DOM that matches a specified CSS selector in the document.
- Save the
index.html
file; refresh theindex
page in the browser. Notice the output is hidden until you click on thezzz
button.
Step 7
-
We must calculate and display the wake up hours when user clicks on the
zzz
button. Let's focus on the second part: displaying the hours. -
At the moment, there is a
<p>
element that holds the hours:
<p>11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
- Here is a sample code to access and update the content of this
<p>
element:
let hours = // get the <p> element
hours.innerText = // string containing hours
- Similar to how we accessed the output
<div>
, we can access this<p>
element by giving it a class attribute such as<p class="hours">
let hours = document.querySelector('.hours');
hours.innerText = "placeholder for hours!";
- We can, alternatively, give it an ID attribute
<p id="hours">
:
let hours = document.getElementById('hours');
hours.innerText = "placeholder for hours!";
- The ID attribute specifies a unique id for an HTML element.
The ID must be unique within the HTML document, although your webpage will still work if you use the same ID for multiple elements!
- The
getElementById()
method returns the element that has the ID attribute with the specified value.
- Let's use ID attribute on the
<p>
element; update thehandleOnClickEvent
function as follows:
<script>
function handleOnClickEvent() {
let output = document.querySelector('.output');
output.style.display = 'block';
let hours = document.getElementById('hours');
hours.innerText = "placeholder for hours!";
}
</script>
Instead of
getElementById('hours')
we could usequerySelector('#hours')
. The difference between the two is not important to us now, but if you are interested, see this stack-overflow query
- Save the
index.html
file; refresh theindex
page in the browser. Notice when you click onzzz
button, the output is displayed but the hours are now replaced withplaceholder for hours!
Step 8
We are content with the content and styling (pun intended!). Let's focus on the algorithm:
- When the
zzz
button is clicked we want to record the current time - Allow 14 minutes to fall sleep
- Create 6 cycles of 90 minutes each
- Display the cycles as suggested wake up times.
The date
object
- Let's see how we can get the current time (date and time); click on the
play
button below and "run" the code snippet
let time = Date.now(); console.log(time);
- Note the output is an integer! Let's find out what this value is; Google: MDN JavaScript Date. Follow the first suggested result and read the docs!
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a number that represents milliseconds since 1/1/1970 UTC.
Further notice the following methods:
Date.now()
Returns the numeric value corresponding to the current time; the number of milliseconds elapsed since 1/1/1970 00:00:00 UTC, with leap seconds ignored.
Date.prototype.toLocaleTimeString()
Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.
The keyword
prototype
indicatestoLocaleTimeString()
is an instance method (unlikenow()
which is a static method).
- Let's try the code below
let today = new Date(); console.log(today.toLocaleTimeString());
- So we can get the current time and print it out! Next we will write JavaScript code to implement our algorithm.
Step 9
Take a moment and read through the code below; feel free to create a play-ground (click on play
button) and experiment with it. I expect that you understand the code (since you've done programming in Java/C++).
let now = Date.now(); let minute = 60 * 1000; // milliseconds let hours = ""; now += 14 * minute; // fall sleep // compute sleep cycles for (let c = 1; c <= 6; c++) { now += 90 * minute; let cycle = new Date(now); hours += cycle.toLocaleTimeString(); if (c < 6) { hours += " or "; } } console.log(hours);
We need to plug this code into the <script>
element:
<script>
function handleOnClickEvent() {
let output = document.querySelector('.output');
output.style.display = 'block';
let now = Date.now();
let minute = 60 * 1000; // miliseconds
let hours = "";
now += 14 * minute; // fall sleep
// compute sleep cycles
for (let c = 1; c <= 6; c++) {
now += 90 * minute;
let cycle = new Date(now);
hours += cycle.toLocaleTimeString();
if (c < 6) {
hours += " or ";
}
}
let hoursElm = document.getElementById('hours');
hoursElm.innerText = hours;
}
</script>
- Save the
index.html
file; refresh theindex
page in the browser. You must now have a working application.
Step 10
There are best practices and coding convention when it comes to authoring HTML documents. A good starting point is given on W3School's HTML Style Guide. You can search online for more resources. (You will find many).
We've already followed many of the points made in W3School's HTML Style Guide. We will polish our work by incorporating a few which we've left out.
HTML <!DOCTYPE>
Declaration
- Add to the very top of
index.html
<!DOCTYPE html>
The
<!DOCTYPE>
declaration is not an HTML tag. It is an "information" to the browser about what document type to expect.
Add the lang
Attribute and Character Encoding
- Add to
lang
attribute to the<html>
tag:
<html lang="en-us">
- Use the
<meta>
tag to declare the character encoding used in your HTML document. (Place it right after the<head>
opening tag.)
<meta charset="UTF-8">
To ensure proper interpretation and correct search engine indexing, both the language and the character encoding should be defined as early as possible in an HTML document.
Setting The Viewport
- We can use the
<meta>
tag for setting the viewport.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
The viewport gives the browser instructions on how to control the page's dimensions and scaling. It is needed for responsive web design which aims to make your web page look good on all devices.
Separate the "style" from "content"
It is considered a good practice to separate style from content. This means using <style>
element instead of inline style
attributes. It is considered a better practice to take this a level further and move all the styling into a separate file.
-
Create a
style.css
file (in the same folder whereindex.html
is). -
Move everything inside the
<style></style>
tag tostyle.css
. -
Delete the
style
element fromindex.html
-
Add the following where
<style>
element used to be:
<link rel="stylesheet" href="style.css">
Separate JavaScript from HTML
We can make a similar argument to that made earlier about separating style from the content, for separating "scripts" from the content.
-
Create a
script.js
file (in the same folder whereindex.html
is). -
Move everything inside the
<script></script>
tag toscript.js
. -
Update the
<script>
element
<script src="script.js"></script>
Exercise 1
Visit sleepyti.me and click on the zzz
button; notice the wake up hours are color coded. Create the same effect in our app (use the same colors).
Solution
We can wrap each wake up hour in a <span></span>
tag with a unique ID for each cycle:
<p id="hours">
<span id="cycle-1">11:44 PM</span> or
<span id="cycle-2">1:14 AM</span> or
<span id="cycle-3">2:44 AM</span> or
<span id="cycle-4">4:14 AM</span> or
<span id="cycle-5">5:44 AM</span> or
<span id="cycle-6">7:14 AM</span>
</p>
The
<span>
tag is much like the<div>
element, but<div>
is a block-level element and<span>
is an inline element.
We can then update our style.css
file to assign the desired colors to each "cycle":
#cycle-1 {
color: rgb(168, 39, 254);
}
#cycle-2 {
color: rgb(154, 3, 254);
}
#cycle-3 {
color: rgb(150, 105, 254);
}
#cycle-4 {
color: rgb(140, 140, 255);
}
#cycle-5 {
color: rgb(187, 187, 255);
}
#cycle-6 {
color: rgb(143, 254, 221);
}
- Note CSS ID selector starts with
#
- Moreover, notice we can specify colors by their
rgb
values.
I picked up the values by inspecting the output on sleepyti.me.
To generate this output programmatically, we need to update our JavaScript code:
function handleOnClickEvent() {
let output = document.querySelector('.output');
output.style.display = 'block';
let now = Date.now();
let minute = 60 * 1000; // miliseconds
let hours = document.getElementById('hours');
hours.innerText = ""; // cleanup exisitng content
now += 14 * minute; // fall sleep
// compute sleep cycles
for (let c = 1; c <= 6; c++) {
now += 90 * minute;
let cycle = new Date(now);
let span = document.createElement("span");
span.id = "cycle-" + c;
span.innerText = cycle.toLocaleTimeString();
hours.appendChild(span);
if (c < 6) {
let or = document.createTextNode(" or ");
hours.appendChild(or);
}
}
}
- The createElement() method creates an HTML Element Node with the specified name.
- The createTextNode() method creates a Text Node with the specified text.
- The appendChild() method appends a node as the last child of a node.
Exercise 2
Visit sleepyti.me and notice the calculate
button which comes after "I plan to FALL ASLEEP at..." clause. Give it a try and understand the functionality. Then, try to reproduce it.
Solution
We need to make some changes to the content:
<p>I plan to fall sleep at...</p>
<select id="hh">
<option>(hour)</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
</select>
<select id="mm">
<option>(minute)</option>
<option>00</option>
<option>05</option>
<option>10</option>
<option>15</option>
<option>20</option>
<option>25</option>
<option>30</option>
<option>35</option>
<option>40</option>
<option>45</option>
<option>50</option>
<option>55</option>
</select>
<select id="ampm">
<option>PM</option>
<option>AM</option>
</select>
<br>
<br>
<button onclick="handleOnClickEvent();">CALCULATE</button>
The
<select>
element is used to create a drop-down list.The
<br>
tag inserts a single line break
We further need to adjust the output content:
<div class="output">
<p>If you fall sleep at the specified time above, you should try to wake up at one of the following times:</p>
<p id="hours">11:44 PM or 1:14 AM or 2:44 AM or 4:14 AM or 5:44 AM or 7:14 AM</p>
<p>A good night's sleep consists of 5-6 complete sleep cycles.</p>
</div>
Now, we must update our JavaScript code to base its sleep cycle calculation on the time specified by the user (using the drop-down lists). So, take out the following statement:
let now = Date.now();
and replace it with the following:
let hh = document.getElementById("hh").value;
let mm = document.getElementById("mm").value;
let ampm = document.getElementById("ampm").value;
hh = ampm === "PM" ? hh + 12 : hh;
let now = new Date();
now.setHours(hh);
now.setMinutes(mm);
now = now.valueOf();
The
value
property sets or returns the value of the selected option in a drop-down list.The
valueOf()
method returns the primitive value of a Date object.
Finally, we must adjust our JavaScript code to not take into account the "14 minutes" to fall sleep since the assumption is that the user falls sleep at the specified time. So, comment out the following line:
now += 14 * minute;
There is a bug 🐛 in the solution provided here. We will revisit this in future lectures as an opportunity to work with the built-in debugger in Chrome/FireFox Developer Tools.
HTML
HTML (HyperText Markup Language) is used to lay out the structure of a webpage.
HTML is made up of tags.
- Tags generally come in pairs, with data being in between the tags.
- Tags are indented to help visualize their hierarchy, but any indentation is purely stylistic.
- Tags can also have attributes, which are data fields, sometimes required and sometimes optional, that provide additional information to the browser about how to render the data.
We will explore some common tags below.
Basic structure
<!DOCTYPE html>
is placed at the start of an HTML file to indicate to the browser that HTML5 is being used.<html></html>
: contents of website<head></head>
: metadata about the page that is useful for the browser when displaying the page<title></title>
: title of the page<body></body>
: body of the page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
Basic tags
Explore the CodePen below for basic HTML tags and their effect.
See the Pen HTML Basic tags by Ali Madooei (@madooei) on CodePen.
Lists
<ul></ul>
: unordered list<ol></ol>
: ordered list<li></li>
: list item (must be inside either<ul></ul>
or<ol></ol>
)
See the Pen HTML List tags by Ali Madooei (@madooei) on CodePen.
Link and Image
<a href="path/to/hello.html">Click here!</a>
: link tohello.html
, some URL, or some other content marked byid
by passing#id
tohref
<img src="path/to/img.jpg" height="200" width="300">
: image stored atsrc
attribute, which can also be a URL- note that this is a single tag without an end tag
- both
height
andwidth
are optional (if one is omitted, the browser will auto-size the image), and can also take a percentage:height=50%
to automatically scale the image to a certain portion of the page
See the Pen HTML img tag by Ali Madooei (@madooei) on CodePen.
Table
<table></table>
: table<tr></tr>
: table row (must be inside<table></table>
)<th></th>
: table header (must be inside<td></td>
)<td></td>
: table data (cell) (must be inside<td></td>
)
See the Pen HTML table tag by Ali Madooei (@madooei) on CodePen.
Forms
You can create forms in HTML to collect data; we will explore this later. Here is a CodePen for illustration of some basic form tags:
See the Pen HTML Basic form tags by Ali Madooei (@madooei) on CodePen.
div
and span
Two special tags allow us to break up a our webpage into sections:
<div></div>
: vertical division of a webpage<span></span>
: section of a webpage inside, for example, text
Both <div></div>
and <span></span>
don't really do much by themselves, but they allow for the labelling of sections of a webpage.
Different sections of a webpage can be referenced with the
id
andclass
attributes.id
s uniquely identify elements, but there can be an arbitrary number of elements with a givenclass
.
DOM
The Document Object Model is a way to conceptualize webpages by representing them as a interconnected hierarchy of nodes. In HTML, the nodes of the DOM would be the different tags and their contained data, with the <html></html>
tag being at the very top of the tree. While this might seem a little unintuitive at first, this model will become very useful in the future.
See the Pen HTML DOM by Ali Madooei (@madooei) on CodePen.
You will find a wealth of resources on HTML (and Web Development in general) at MDN Web Docs and W3School.
CSS
CSS (Cascading Style Sheets) is a language used to interact with and style HTML, changing the way it looks according to a series of rules. CSS is what makes websites look nice.
CSS can be applied to HTML in a variety of ways:
-
The inline
style
attribute:See the Pen Inline CSS by Ali Madooei (@madooei) on CodePen.
-
The internal style defined inside
<style></style>
tags, inside the<head>
section of HTML.See the Pen Internal CSS by Ali Madooei (@madooei) on CodePen.
The CodePen above is styled with the following:
<style> div { color: blue; } #danger { color: red; } .highlight { background-color: yellow; } </style>
-
A separate
.css
file:- add
<link rel="stylesheet" href="path/to/styles.css">
to the header, - move the CSS code (same format as used inside the
<style></style>
tags.
This is often an even better paradigm because it separates two distinctly different things: structure (HTML) and style (CSS), while also being easier to manage and read.
- add
CSS Selectors
CSS selectors are used to select different parts of an HTML page to style in particular ways. In the above example, div
, #danger
and .highlight
are CSS selectors (to select all div
elements, the element with id="danger
and all elements with class="highlight"
, respectively.)
Here are some fancier ways to work with the selectors:
-
Select
h1
andh2
elementsh1, h2 { color: blue; }
-
Select all
p
elements inside an element withclass="note"
.note p { color: blue; }
-
Select all
input
fields with the attributetype=text
input[type=text] { color: blue; }
Here it gets even fancier:
-
Add two
#
before allh2
elements:h2::before { content: "##"; }
before
is called a pseudo-element! -
Change the color of a button when the cursor is hovering over it.
button:hover { background-color: gray; }
hover
is called a pseudo-class!
CSS Properties
Here are some common CSS properties:
background-color: teal;
color: blue; /* sets the content (text) color */
/* color can be one of ~140 named colors, or a hexadecimal value that represents an RGB value */
text-align: left; /* other possible values are center, right, or justify */
height: 150px; /* sets the height of an area */
width: 150px; /* sets the width of an area */
/* arguments in pixels often can take a percentage or relative values too */
margin: 30px; /* sets the margin around all four sides of an area */
/* margin also be broken up into "margin-left", "margin-right", "margin-top", and "margin-bottom" */
padding: 20px; /* sets the padding around text inside an area */
/* padding be broken up the same way as "margin" */
border: 3px solid blue; /* sets a border around an area */
font-family: Arial, sans-serif; /* sets the font family to be used */
font-size: 28px; /* sets the font size */
font-weight: bold; /* sets the font weight to quality, a relative measure ("lighter"), or a number ("200") */
There are lots of CSS properties that can be used in a lot of different ways. Check out the wonderfully extensive documentation for more information.