全栈学习笔记

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:

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>
<h1 id="bottom">This is the bottom! </h1>

Let’s review what you’ve learned this lesson:

  1. 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.
  2. The <html> element will contain all of your HTML code.
  3. Information about the web page, like the title, belongs within the <head> of the page.
  4. You can add a title to your web page by using the <title> element, inside of the head.
  5. A webpage’s title appears in a browser’s tab.
  6. Anchor tags (<a>) are used to link to internal pages, external pages or content on the same page.
  7. You can create sections on a webpage and jump to them using <a> tags and adding ids to the elements you wish to jump to.
  8. Whitespace between HTML elements helps make code easier to read while not changing how elements appear in the browser.
  9. Indentation also helps make code easier to read. It makes parent-child relationships visible.
  10. Comments are written in HTML using the following syntax: <!-- comment -->.

Take some time to edit the workspace you created and observe how it changes!

<!DOCTYPE html>
<html>

<head>
<title>Brown Bears</title>
</head>

<body>
<nav>
<a href="./index.html">Brown Bear</a>
<a href="./aboutme.html">About Me</a>
</nav>
<h1>The Brown Bear</h1>
<nav>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#habitat">Habitat</a></li>
<li><a href="#media">Media</a></li>
</ul>
</nav>
<div id="introduction">
<h2>About Brown Bears</h2>
<p>The brown bear (<em>Ursus arctos</em>) is native to parts of northern Eurasia and North America. Its conservation status is currently <strong>Least Concern</strong>.<br /><br /> There are many subspecies within the brown bear species, including the
Atlas bear and the Himalayan brown bear.</p>
<a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank">Learn More</a>
<h3>Species</h3>
<ul>
<li>Arctos</li>
<li>Collarus</li>
<li>Horribilis</li>
<li>Nelsoni (extinct)</li>
</ul>
<h3>Features</h3>
<p>Brown bears are not always completely brown. Some can be reddish or yellowish. They have very large, curved claws and huge paws. Male brown bears are often 30% larger than female brown bears. They can range from 5 feet to 9 feet from head to toe.</p>
</div>
<div id="habitat">
<h2>Habitat</h2>
<h3>Countries with Large Brown Bear Populations</h3>
<ol>
<li>Russia</li>
<li>United States</li>
<li>Canada</li>
</ol>
<h3>Countries with Small Brown Bear Populations</h3>
<p>Some countries with smaller brown bear populations include Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India, Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and Uzbekistan.</p>
</div>
<div id="media">
<h2>Media</h2>
<img src="https://content.codecademy.com/courses/web-101/web101-image_brownbear.jpg" />
<video src="https://content.codecademy.com/courses/freelance-1/unit-1/lesson-2/htmlcss1-vid_brown-bear.mp4" height="240" width="320" controls>Video not supported</video>
</div>
</body>

</html>

<!DOCTYPE html>
<html>
<head>
<title>Everyday with Isa</title>
</head>
<body>
<a href="#contact"><img src="https://content.codecademy.com/courses/learn-html/elements-and-structure/profile.jpg" />
</a>
<h3>by Isabelle Rodriguez | 1 day ago</h3>
<h1>An Insider’s Guide to NYFW</h1>
<img src="https://content.codecademy.com/courses/learn-html/elements-and-structure/image-one.jpeg"/>
<p>
<a href="https://en.wikipedia.org/wiki/New_York_Fashion_Week" target="_blank">NYFW</a> can be both amazingly fun & incredibly overwhelming, especially if you’ve never been. Luckily, I’m here to give you an insider’s guide and make your first show a pleasurable experience. By taking my tips and tricks, and following your gut, you’ll have an unforgettable experience!
</p>
<h2>Getting Tickets & Picking the Shows</h2>
<img src="https://content.codecademy.com/courses/learn-html/elements-and-structure/image-two.jpeg"/>
<p>
If you’re lucky or connected you can get an invite, sans the price tag. But I wasn’t so lucky or connected my first 2 years so I’m here to help you out. First, plan out which shows are most important to you and make a schedule and this is a biggie: SET A BUDGET. If you’re worrying about blowing your cash the whole time you won’t have fun. Then check out prices, days, and times and prioritize the designers you want to see most. Lastly, purchase your tickets and get excited!
</p>
<h2>Dressing for the Shows</h2>
<img src="https://content.codecademy.com/courses/learn-html/elements-and-structure/image-three.jpeg"/>
<p>
Always be true to your own sense of style, if you don’t you’ll be uncomfortable the whole time and it will show. Remember, NYFW is about expressing yourself and taking in what the designers have chosen to express through their new lines. Also it’s important to wear shoes you’ll be comfortable in all day. Obviously you want to look good, but you’ll be on your feet all day long, so be prepared.
</p>
<h4>Related Content</h4>
<ul>
<li>How To Style Boyfriend Jeans</li>
<li>When Print Is Too Much</li>
<li>The Overalls Trend</li>
<li>Fall’s It Color: Blush</li>
</ul>
<div id="contact">
<p>
<strong>email</strong>: isa@fashionblog.com | <strong>phone</strong>: 917-555-1098 | <strong>address</strong>: 371 284th St, New York, NY, 10001
</p>
</div>
</body>
</html>

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.
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Aguillar Family Wine Festival</title>
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">
</head>

<body>
<header>
<h1>Annual Aguillar Family Wine Festival</h1>
</header>

<div class="container">
<table>
<thead>
<tr>
<th colspan="2" scope="col">
<h1>Wine Festival Schedule</h1>
</th>
</tr>
<tr>
<th scope="col">
<h2>Time</h2>
</th>
<th scope="col">
<h2>Event</h2>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="left"><h3>12:00 PM</h3></td>
<td><h3>Welcome Reception</h3></td>
</tr>
<tr>
<td class="left"><h3>01:00 PM</h3></td>
<td><h3>Storytelling & Tasting</h3></td>
</tr>
<tr>
<td class="left"><h3>02:00 PM</h3></td>
<td><h3>Wine Luncheon</h3></td>
</tr>
<tr>
<td class="left"><h3>03:00 PM</h3></td>
<td><h3>Aguillar Family Wines</h3></td>
</tr>
<tr>
<td class="left"><h3>04:00 PM</h3></td>
<td><h3>Wine & Cheese Tasting</h3></td>
</tr>
</tbody>
</table>


</div>

<footer>
<h3>Contact</h3>
<h3>Location</h3>
<h3>Privacy Policy</h3>
</footer>
</body>

</html>

body {
background-color: #242f44;
color: white;
font-family: 'Oswald', sans-serif;
}

header {
text-align: center;
margin-top: 5px;
}

h1 {
font-size: 36px;
padding: 15px;
color: #8c6b48;
background-color: white;
}

h2 {
font-size: 24px;
padding: 15px;
text-transform: uppercase;
}

h3 {
font-size: 20px;
padding: 15px;
text-transform: uppercase;
text-align: left;
margin-left: 20px;
font-weight: 500;
line-height: 2.7;
letter-spacing: 0.8px;
}

th {
border: 2px solid #8c6b48;
}

table {
text-align: center;
margin: 20px auto;
}

td {
border: 2px solid #8c6b48;
width: 300px;
}

footer {
margin-top: 50px;
text-align: center;
position: fixed;
width: 100%;
bottom: 5px;
background-color: #242f44;
z-index: 5;
}
footer h3 {
display: inline-block;
font-size: 14px;
background-color: #242f44;
}

.container {
max-width: 940px;
margin: 0 auto;
height: 800px;
}


.left {
width: 150px;
}

image-20250605143129148

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">
</form>

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">
<h1>Creating a form</h1>
<p>Looks like you want to learn how to create an HTML form. Well, the best way to learn is to play around with it.</p>
</form>


Copy to Clipboard

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">
<input type="text" name="first-text-field">
</form>


Copy to Clipboard

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:

rendered empty text field from input element type='text'

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:

rendered filled text field which reads 'important details'

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">
<input type="text" name="first-text-field" value="already pre-filled">
</form>


Copy to Clipboard

Which renders:

pre-filled text box due to assigned `value` attribute

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>
<label for="city">Ideal city to visit?</label>
<input type="text" list="cities" id="city" name="city">

<datalist id="cities">
<option value="New York City"></option>
<option value="Tokyo"></option>
<option value="Barcelona"></option>
<option value="Mexico City"></option>
<option value="Melbourne"></option>
<option value="Other"></option>
</datalist>
</form>


Copy to Clipboard

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:input field with a label 'Ideal city to visit?'

And when field is selected:clicking on the input field reveals a dropdown  list

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.

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<title>Textarea element</title>
</head>
<body>
<section id="overlay">
<img src="https://content.codecademy.com/courses/web-101/unit-6/htmlcss1-img_burger-logo.svg" alt="Davie's Burgers Logo" id="logo">
<hr>
<form action="submission.html" method="POST">
<h1>Create a burger!</h1>
<section class="protein">
<label for="patty">What type of protein would you like?</label>
<input type="text" name="patty" id="patty">
</section>
<hr>
<section class="patties">
<label for="amount">How many patties would you like?</label>
<input type="number" name="amount" id="amount">
</section>
<hr>
<section class="cooked">
<label for="doneness">How do you want your patty cooked</label>
<br>
<span>Rare</span>
<input type="range" name="doneness" id="doneness" value="3" min="1" max="5">
<span>Well-Done</span>
</section>
<hr>
<section class="toppings">
<span>What toppings would you like?</span>
<br>
<input type="checkbox" name="topping" id="lettuce" value="lettuce">
<label for="lettuce">Lettuce</label>
<input type="checkbox" name="topping" id="tomato" value="tomato">
<label for="tomato">Tomato</label>
<input type="checkbox" name="topping" id="onion" value="onion">
<label for="onion">Onion</label>
</section>
<hr>
<section class="cheesy">
<span>Would you like to add cheese?</span>
<br>
<input type="radio" name="cheese" id="yes" value="yes">
<label for="yes">Yes</label>
<input type="radio" name="cheese" id="no" value="no">
<label for="no">No</label>
</section>
<hr>
<section class="bun-type">
<label for="bun">What type of bun would you like?</label>
<select name="bun" id="bun">
<option value="sesame">Sesame</option>
<option value="potatoe">Potato</option>
<option value="pretzel">Pretzel</option>
</select>
</section>
<hr>
<section class="sauce-selection">
<label for="sauce">What type of sauce would you like?</label>
<input list="sauces" id="sauce" name="sauce">
<datalist id="sauces">
<option value="ketchup"></option>
<option value="mayo"></option>
<option value="mustard"></option>
</datalist>
</section>
<hr>
<section class="extra-info">
<label for="extra">Anything else you want to add?</label>
<br>
<textarea id="extra" name="extra" rows="3" cols="40"></textarea>
</section>
<hr>

<section class="submission">
<!--Add your code below-->
<input type="submit" value="Submit">

</section>

</form>
</section>
</body>
</html>

body {
background-color: rgb(57, 169, 219);
font-family: Rubik, Arial;
}

form {
text-align: center;
line-height: 30px;
height: 80%;
overflow: auto;
}

form hr {
width: 15%;
}

h1 {
text-align: center;
}

#overlay {
width: 80%;
margin: 3% auto;
height: 95vh;
background-color: rgba(255, 255, 255, 0.9);
border-radius: 40px;
}

#logo {
height: 100px;
display: block;
margin: auto;
}


.toppings label, .cheesy label {
margin-right: 25px;
}

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
<title>Forms Review</title>
</head>
<body>
<section id="overlay">
<img src="https://content.codecademy.com/courses/web-101/unit-6/htmlcss1-img_burger-logo.svg" alt="Davie's Burgers Logo" id="logo">
<hr>
<h1>Thanks for your submission!</h1>
</section>
</body>
</html>

console.log = () => {}
const { expect } = require('chai');
const rewire = require('rewire');
const Vue = require('vue');

describe('', function () {
it('', function () {
let appModule = rewire("../js/app.js");
let vueApp = appModule.__get__("app");
expect(vueApp).to.exist();
});
});

In this lesson we went over:

  • The purpose of a <form> is to allow users to input information and send it.
  • The <form>‘s action attribute determines where the form’s information goes.
  • The <form>‘s method attribute determines how the information is sent and processed.
  • To add fields for users to input information we use the<input>element and set thetypeattribute 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 the list attribute will pair the <input> with a <datalist> element if the list of <input> and the id of <datalist> are the same.
    • Setting type to "submit" creates a submit button.
  • 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, the name of the fields that accept input and the value of those fields are sent as name=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 -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sign Up Page</title>
<link rel="stylesheet" href="style.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Fjalla+One" rel="stylesheet">
</head>
<body>
<section class="overlay">
<h1>Sign Up</h1>
<p>Create an account:</p>
<form action="submission.html" method="GET">
<label for="username">Username:</label>
<br>
<input id="username" name="username" type="text" required minlength="3" maxlength="15">
<br>
<label for="pw">Password:</label>
<br>
<!--Add the pattern attribute to the input below-->
<input id="pw" name="pw" type="password" required minlength="8" maxlength="15">
<br>
<input type="submit" value="Submit">
</form>
</section>
</body>
</html>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Required</title>
<link rel="stylesheet" href="style.css" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Fjalla+One" rel="stylesheet">
<script type="text/javascript" src="login.js" defer></script>
</head>
<body>
<section class="overlay">
<h1 id="message"></h1>
<a href="index.html">Go back</a>
</section>
</body>
</html>

body {
background-color: #59CD90;
color: #3FA7D6;
font-family: "Fjalla One", Arial;
}

form {
line-height: 25px;
}

h1 {
font-size: 3em;
overflow: break;
}

.overlay {
width: 80%;
min-width: 30%;
margin: 3% auto;
display: block;
padding: 2%;
height: 90vh;
background-color: rgba(255, 255, 255, 0.9);
border-radius: 40px;
text-align: center;
}

const message = document.getElementById('message');
const param = new URLSearchParams(window.location.search);
const username = param.get('username');
const pw = param.get('pw');

if(username.toLowerCase() === 'codecademy' && pw === 'ilovecoding'){
message.innerHTML = 'We love coding too!';
} else if(!username || !pw){
message.innerHTML = 'Add some client-side validation!';
} else {
message.innerHTML = 'Hurray for client-side validation!';
}

console.log = () => {}
const { expect } = require('chai');
const rewire = require('rewire');
const Vue = require('vue');

describe('', function () {
it('', function () {
let appModule = rewire("../js/app.js");
let vueApp = appModule.__get__("app");
expect(vueApp).to.exist();
});
});

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.

Image shows non-semantic code full of random elements. The semantic code is clean and easy to understand since everything is labeled.

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>
<header>
<h1>Types of Sports</h1>
</header>
<article>
<h3>Baseball</h3>
<p>
The first game of baseball was played in Cooperstown, New York in the summer of 1839.
</p>
</article>
</main>


Copy to Clipboard

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>
<p>Email me at Codey@Codecademy.com</p>
</footer>


Copy to Clipboard

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.

<!DOCTYPE html>
<html>
<body>
<header>
<h1>Navigational Links</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#posts">Posts</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<p>This is where the main content will go once the page is built out!</p>
</main>

<footer>
<p>Contact me at +1 234 567 8910 </p>
</footer>

</body>
</html>

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.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header>
<h1>Navigational Links</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#posts">Posts</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>

<main>
<section>
<article>
<h2>Facts About Dogs</h2>
<p>
Dogs have a sense of time. It's been proven that they know the difference between a hour and five. If conditioned to, they can predict future events, such as regular walk times.
</p>
</article>
<aside>
<p>A study was conducted on dogs being away from their owners for varying hours and the studies show that dogs who were away from their owners the longest showed the greatest amount of affection!
</p>
</aside>
</section>
<figure>
<img src="https://content.codecademy.com/courses/SemanticHTML/dogimage.jpeg"/>
<figcaption>A cute dog.</figcaption>
</figure>
<audio controls>
<source src="https://content.codecademy.com/courses/SemanticHTML/dogBarking.mp3" type="audio/mp3">
</audio>
<video src="https://content.codecademy.com/courses/SemanticHTML/dog-video.mp4" controls>
</video>
<embed src="https://content.codecademy.com/courses/SemanticHTML/dog-on-beach.gif"/>

</main>

<footer>
<p>Contact me at +1 234 567 8910 </p>
</footer>

</body>
</html>

CSS

References

Setup and Syntax

table labeling different components of CSS syntaxes

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>
<style>


</style>
</head>


Copy to Clipboard

After adding opening and closing <style> tags in the head section, you can begin writing CSS code.

<head>
<style>
p {
color: red;
font-size: 20px;
}
</style>
</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 {
color: green;
}


Copy to Clipboard

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:

* { 
font-family: Verdana;
}
<p class='brand'>Sole Shoe Company</p>


Copy to Clipboard

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 {

}


Copy to Clipboard

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 {
color: green;
}

.bold {
font-weight: bold;
}


Copy to Clipboard

Then, you could include both of these classes on one HTML element like this:

<h1 class='green bold'> ... </h1>


Copy to Clipboard

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>


Copy to Clipboard

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 {

}


Copy to Clipboard

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]{
color: magenta;
}

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'>
<img src='/images/seasons/warm/summer.jpg'>


Copy to Clipboard

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'] {
height: 50px;
}

img[src*='summer'] {
height: 100px;
}


Copy to Clipboard

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 string winter

    and sets theheight to 50px.

  • The second ruleset looks for an img element with an attribute of src that contains the string 'summer', and sets the height to 100px.

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 {
background-color: lime;
}


Copy to Clipboard

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>


Copy to Clipboard
h1 {
color: red;
}

.headline {
color: firebrick;
}


Copy to Clipboard

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 {

}


Copy to Clipboard

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'>
<li> ... </li>
<li> ... </li>
<li> ... </li>
</ul>


Copy to Clipboard

The nested <li> elements are descendants of the <ul> element and can be selected with the descendant combinator like so:

.main-list li {

}


Copy to Clipboard

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 {
color: blue;
}

.main p {
color: red;
}


Copy to Clipboard

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 {
font-family: Georgia;
}

.menu {
font-family: Georgia;
}


Copy to Clipboard

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, 
.menu {
font-family: Georgia;
}


Copy to Clipboard

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 {
font-family: Garamond;
}


Copy to Clipboard

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-family: 'Courier New';
}


Copy to Clipboard

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 {
font-size: 18px;
}


Copy to Clipboard

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 {
font-weight: bold;
}


Copy to Clipboard

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 {
text-align: right;
}


Copy to Clipboard

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 {
color: red;
background-color: blue;
}
Copy to Clipboard

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 {
opacity: 0.5;
}
Copy to Clipboard

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 {
background-image: url('https://www.example.com/image.jpg');
}
  1. The background-image property will set the element’s background to display an image.
  2. The value provided to background-imageis a url. The urlshould be a URL to an image. The url 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 named mountains.jpg, the relative file path would look like below:
.main-banner {
background-image: url('images/mountains.jpg');
}

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 {
color: blue !important;
}

.main p {
color: red;
}

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:

  1. The dimensions(weight and height) of an element’s box.
  2. The borders [^2]of an element’s box.
  3. The paddings of an element’s box.
  4. 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 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.

image-20250606195423210

CSS Box Model Diagram

Height and Width

p {
height: 80px;
width: 240px;
}


Copy to Clipboard

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, or thick.
  • style—The design of the border. Web browsers can render any of 10 different styles. Some of these styles include: none, dotted, and solid.
  • color—The color of the border. Web browsers can render colors using a few different formats, including 140 built-in color keywords.
p {
border: 3px solid coral;
}

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 {
height: 80px;
width: 240px;
border: solid coral;
}

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 {
border: 3px solid blue;
border-radius: 5px;
}


Copy to Clipboard

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 {
height: 60px;
width: 60px;
border: 3px solid blue;
border-radius: 50%;
}


Copy to Clipboard

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 {
border: 3px solid coral;
padding: 10px;
}


Copy to Clipboard

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 descriptionpadding-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 {
border: 3px solid fuchsia;
padding-bottom: 10px;
}


Copy to Clipboard

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:

You can specify these properties in a few different ways:

4 Values
p.content-header {
padding: 6px 11px 4px 9px;
}


Copy to Clipboard

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 {
padding: 5px 10px 20px;
}


Copy to Clipboard

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 {
padding: 5px 10px;
}


Copy to Clipboard

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 {
border: 1px solid aquamarine;
margin: 20px;
}


Copy to Clipboard

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:

Each property affects the margin on only one side of the box, providing more flexibility in customization.

p {
border: 3px solid DarkSlateGrey;
margin-right: 15px;
}


Copy to Clipboard

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:

You can specify these properties in a few different ways:

4 Values
p {
margin: 6px 10px 5px 12px;
}


Copy to Clipboard

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 {
margin: 5px 12px 4px;
}


Copy to Clipboard

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 {
margin: 20px 10px;
}


Copy to Clipboard

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

image-20250607212822894

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 {
margin-right: 20px;
}

#img-two {
margin-left: 20px;
}


Copy to Clipboard

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 {
margin-bottom: 30px;
}

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


Copy to Clipboard

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.

Diagram of box model vertical margins.

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 {
min-width: 300px;
max-width: 600px;
}


Copy to Clipboard

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 {
min-height: 150px;
max-height: 300px;
}


Copy to Clipboard

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 {
overflow: scroll;
}


Copy to Clipboard

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>
<li>Explore</li>
<li>Connect</li>
<li class="future">Donate</li>
</ul>


Copy to Clipboard
.future {
visibility: hidden;
}


Copy to Clipboard

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 to display, 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>


Copy to Clipboard
h1 {
border: 1px solid black;
height: 200px;
width: 300px;
padding: 10px;
}


Copy to Clipboard

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

image-20250608110956227

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.

* {
box-sizing: border-box;
}


Copy to Clipboard

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>


Copy to Clipboard
* {
box-sizing: border-box;
}

h1 {
border: 1px dashed #4f768e;
height: 150px;
width: 200px;
padding: 20px;
}


Copy to Clipboard

image-20250608111704367

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:

  1. In the default box model, box dimensions are affected by border thickness and padding.
  2. The box-sizing property controls the box model used by the browser.
  3. The default value of the box-sizing property is content-box.
  4. The value for the new box model is border-box.
  5. 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:

Diagram of block-level elements

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.