sábado, 22 de abril de 2023

C4 - HTML AND CSS IN DEPTH - COURSE 4/9

  META FRONT END DEVELOPER PROFESSIONAL CERTIFICATE

HTML AND CSS IN DEPTH


Working with labs in this course

Throughout this course, you will be completing labs in a virtual coding environment. The purpose of these labs is to give you an opportunity to apply what you learn. You will be doing things like creating a basic login form for a website, a table booking form and a web page for rating a video. And that's just in the first module! In module 2 you'll create a grid layout and a restaurant menu and you'll practice the transform and transition properties in CSS. And, in the final module, there is a lab that will allow you to work in VS Code for the portfolio project without downloading it to your computer.

To complete some of the labs you need to be able to see your rendered HTML in a browser. To view the rendered HTML on a web page follow the step-by-step instructions below.

Step 1: Save the file.

Step 2: Click on 'Go live' at the bottom right of your editor.


Once the server is up and running you'll see the exposed port.


Step 3: Click on browser preview.


Step 4: Enter the url as http://localhost:5500


Step 5: Check that the web page displays.

After completing your lab, don't forget to close the server. You can close the server by clicking on the exposed Port number (e.g. 5500) after completing the lab.


You should see a notification like this which confirms the server has been stopped.



Semantic HTML cheat sheet

There are hundreds of semantic tags available to help describe the meaning of your HTML documents. Below is a cheat sheet with some of the most common ones you’ll use in this course and in your development career.

Sectioning tags
Use the following tags to organize your HTML document into structured sections. 

<header>
The header of a content section or the web page. The web page header often contains the website branding or logo.

<nav>
The navigation links of a section or the web page.

<footer>
The footer of a content section or the web page. On a web page, it often contains secondary links, the copyright notice, privacy policy and cookie policy links.

<main>
Specifies the main content of a section or the web page.

<aside>
A secondary set of content that is not required to understand the main content.

<article>
An independent, self-contained block of content such as a blog post or product.

<section>
A standalone section of the document that is often used within the body and article elements.

<details>
A collapsed section of content that can be expanded if the user wishes to view it.

<summary>
Specifies the summary or caption of a <details> element.

<h1><h2><h3><h4><h5><h6>
Headings on the web page. <h1> indicates the most important heading whereas <h6> indicates the least important. 

Content tags

<blockquote>
Used to describe a quotation.

<dd>
Used to define a description for the preceding <dt> element.

<dl>
Used to define a description list.

<dt>
Used to describe terms inside <dl> elements.

<figcaption>
Defines a caption for a photo image.

<figure>
Applies markup to a photo image.

<hr>
Adds a horizontal line to the parent element.

<li>
Used to define an item within a list.

<menu>
A semantic alternative to <ul> tag.

<ol>
Defines an ordered list.

<p>
Defines a paragraph.

<pre>
Used to represent preformatted text. Typically rendered in the web browser using a monospace font.

<ul>
Unordered list

Inline tags

<a>
An anchor link to another HTML document.

<abbr>
Specifies that the containing text is an abbreviation or acronym.

<b>
Bolds the containing text. When used to indicate importance use <strong> instead.

<br>
A line break. Moves the subsequent text to a new line.

<cite>
Defines the title of creative work (for example a book, poem, song, movie, painting or sculpture). The text in the <cite> element is usually rendered in italics.

<code>
Indicates that the containing text is a block of computer code.

<data>
Indicates machine-readable data.

<em>
Emphasizes the containing text.

<i>
The containing text is displayed in italics. Used to indicate idiomatic text or technical terms.

<mark>
The containing text should be marked or highlighted.

<q>
The containing text is a short quotation.

<s>
Displays the containing text with a strikethrough or line through it.

<samp>
The containing text represents a sample.

<small>
Used to represent small text, such as copyright and legal text.

<span>
A generic element for grouping content for CSS styling.

<strong>
Displays the containing text in bold. Used to indicate importance.

<sub>
The containing text is subscript text, displayed with a lowered baseline.

<sup>
The containing text is superscript text, displayed with a raised baseline.

<time>
A semantic tag used to display both dates and times.

<u>
Displays the containing text with a solid underline.

<var>
The containing text is a variable in a mathematical expression.

Embedded content and media tags

<audio>
Used to embed audio in web pages.

<canvas>
Used to render 2D and 3D graphics on web pages.

<embed>
Used as a containing element for external content provided by an external application such as a media player or plug-in application. 

<iframe>
Used to embed a nested web page. 

<img>
Embeds an image on a web page.

<object>
Similar to <embed> but the content is provided by a web browser plug-in.

<picture>
An element that contains one <img> element and one or more <source> elements to offer alternative images for different displays/devices.

<video>
Embeds a video on a web page.

<source>
Specifies media resources for <picture>, <audio> and<video> elements.

<svg>
Used to define Scalable Vector Graphics within a web page.

Table tags

<table>
Defines a table element to display table data within a web page.

<thead>
Represents the header content of a table. Typically contains one <tr> element.

<tbody>
Represents the main content of a table. Contains one or more <tr>elements.

<tfoot>
Represents the footer content of a table. Typically contains one <tr> element.

<tr>
Represents a row in a table. Contains one or more <td> elements when used within <tbody> or <tfoot>. When used within <thead>, contains one or more <th> elements.

<td>
Represents a cell in a table. Contains the text content of the cell.

<th>
Defines a header cell of a table. Contains the text content of the header.

<caption>
Defines the caption of a table element.

<colgroup>
Defines a semantic group of one or more columns in a table for formatting.

<col>
Defines a semantic column in a table.

QUIZ 1 - Practice using semantic tags


Metadata cheat sheet

HTML <meta> tags 
Earlier in the course, you learned about meta tags and how you can leverage them to convey information to search engines to better categorize your pages. We recommend that you keep this cheat sheet handy when building your web applications. The structure of a meta tag is as follows.

Name 
The name of the property can be anything you like, although browsers usually expect a value they understand and can take an action upon. An example would be <meta name="author" content="name"> to state the author of the page. 

Content 
The content field specifies the property's value. For example, you can use <meta name="language" content="english">, to specify the language of the webpage to search engines. 

Charset 
The charset is a special field that lets you specify the character encoding used for the page so that the browser can display it properly. The most frequently used is utf-8, and you would add it to your HTML header as follows: <meta charset="UTF-8">  

HTTP-equiv 
This field stands for HTTP equivalent, and it’s used to simulate HTTP response headers. This is rare to see, and it’s recommended to use HTTP headers over HTML http-equiv meta tags. For example, the next tag would instruct the browser to refresh the page every 30 minutes: <meta http-equiv="refresh" content="30"> 

Basic meta tags (meta tags For SEO) 
<meta name="description"/> provides a brief description of the web page 

<meta name=”title”/> specifies the title of the web page 

<meta name="author" content="name"> specifies the author of the web page  

<meta name="language" content="english"> specifies the language of the web page 

<meta name="robots" content="index,follow" /> tells search engines how to crawl or index a certain page 

<meta name="google"/> tells Google not to show the sitelinks search box for your page when showing search results 

<meta name="googlebot" content=”notranslate” /> tells Google you don’t want to provide an automatic translation for your page if the user uses a different language  

<meta name="revised" content="Sunday, July 18th, 2010, 5:15 pm" /> specifies the last modified date and time on which you have made certain changes 

<meta name="rating" content="safe for kids"> specifies the expected audience for your page 

<meta name="copyright" content="Copyright 2022"> specifies a Copyright 

<meta http-equiv="..."/> tags
 <meta http-equiv="content-type" content="text/html"> specifies the format of the document returned by the server 

<meta http-equiv="default-style"/>  specifies the format of the styling document 

<meta http-equiv="refresh"/> specifies the duration of the page before it’s considered stale 

<meta http-equiv=”Content-language”/> specifies the language of the page 

<meta http-equiv="Cache-Control" content="no-cache"> instructs the browser how to cache your page 

Responsive design/mobile meta tags 
<meta name="format-detection" content="telephone=yes"/> indicates that telephone numbers should appear as hypertext links that can be clicked to make a phone call 

<meta name="HandheldFriendly" content="true"/> specifies that the page can be properly visualized on mobile devices 

<meta name="viewport" content="width=device-width, initial-scale=1.0"/> specifies the area of the window in which web content can be seen

QUIZ 2 - Metadata


Layout design

As you build web pages throughout your career, you’ll notice that many pages follow similar layouts and structures. This is the outcome of many years of research into user interface design and user experience. Different companies, libraries and frameworks then adopt the resulting best practices.

Many examples of these layouts can be seen in the popular bootstrap framework. However, many other frameworks provide similar designs.

Top navbar layout
Websites often have a top navbar layout to provide a set of essential anchor links to the user. These typically link to the main areas of the website, such as product pages, careers pages or contact pages. This provides the visitor to the website with a consistent navigation experience.

Example of a top navbar layout on a web page.

Carousel layout
Product-focused websites often use a large carousel on their homepage to highlight their featured products, discounts and offers. The carousel contains content items that will rotate through the carousel area at a fixed interval.


Blog layout
The blog layout is used to feature multiple content items of differing importance. It is often seen on news websites where new articles will appear on the page each day based on current events.


The layout typically features different-sized feature areas followed by a series of article summary areas that link to full articles.


Dashboard layout
Dashboard layouts are often used in enterprise software for managing various web applications. They typically feature a sidebar for navigation with the main content area containing forms for configuration or reporting data such as graphs and tables. This trendy layout provides a good user experience for business users.


More layouts
You can explore more of these layouts on the bootstrap examples page in the additional resources.

Consider these layouts when building websites and web applications so that you provide your audience with the best user experience possible.

Social media cards

Before Facebook introduced the Open Graph Protocol (OGP), search engine web crawlers, including social media websites, used the internal heuristics of a website to make the best possible guess in terms of the title, description, and preview images to be used for the content. This often led to social networks not completely successfully interpreting the post or information shared in the URL provided. Even today sometimes when you open a link for a website, the preview generated will be an out-of-scale image or a random image that is possibly embedded somewhere within the web page. This is where meta tags come in to help the end-user take better control of their content. 

Over the years, the successful implementation of OGP has led to other social media giants, including sister companies owned by Meta, to adopt the protocol to improve the user experience. These platforms have their own meta tags that prefix and replace ‘og’ that you have encountered earlier in the course.  

Need for social media cards
With the number of users and the use of internet marketing on the rise, user attention is the currency. It is said that a picture is worth a thousand words and the internet is a living proof of it: a caption and image can drive users towards or away from a website. The title and description shared with an URL should summarize the contents of a web page. In some cases, it may refer to generic information about the entire website. While for others you may tailor the social media (SM) card for a specific page on a website that you’re sharing. ‘type’ is an important OGP tag in SM cards that help describe the details of a link such as if it’s a book, article, movie and so on, and provide more detailed metadata for specific types. For example, in case of the music type, you can add details for the song, album, duration or any other information about the song. For a regular user scrolling through social media, the link provided with the image preview has only one chance and a moment’s attention to make a good impression. In such cases, the role of social media cards becomes very important.

The extra time spent by a developer to add social media tags is worth the effort! 

Social media cards and SEO
The internet today is an interconnected graph that is internally a web of URL links, web crawlers, and search engine optimization tools. Together, a web page’s image and title are the store front to invite the user. But the social media cards also play an important role in boosting the rankings for the web crawlers used by search engines. They provide the crawlers with the necessary information to build metadata that eventually helps in ranking websites. Additionally, it also helps track traffic to your website. 

While it’s advised to stick to the required tags in social media cards, a developer can also use auxiliary tags that may be suitable. For example, the use of the video tag that helps to play in-line when displayed on social media websites like Meta. 

Meta also has a dedicated page to assist developers that you can find in the additional resources for this section. 

QUIZ 3 - Open Graph Protocol


QUIZ 4 - Semantic and meta tags

Input types

You already learned about the input HTML tag and how the type property determines the data your users can type in. This cheat sheet should be a reference to decide what type best suits your use case. Most of the inputs go hand in hand with the label tag for best accessibility practices.

Button
This displays a clickable button and it’s mostly used in HTML forms to activate a script when clicked. <input type="button" value="Click me" onclick="msg()" />

Keep in mind you can also define buttons with the <button> tag, with the added benefit of being able to place content like text or images inside the tag.

<button onclick="alert('Are you sure you want to continue?')"> 
    <img src="https://yourserver.com/button_img.jpg" 
        alt="Submit the form" height="64" width="64">
</button> 

Checkbox
Defines a check box allowing single values to be selected or deselected. They are used to let a user select one or more options of a limited number of choices.

<inputtype="checkbox"id="dog"name="dog"value="Dog">
<labelfor="dog">I like dogs</label>
<inputtype="checkbox"id="cat"name="cat"value="Cat">
<labelfor="cat">I like cats</label>

Radio
Displays a radio button, allowing only a single value to be selected out of multiple choices. They are normally presented in radio groups, which is a collection of radio buttons describing a set of related options that share the same "name" attribute.

<inputtype="radio"id="light"name="theme"value="Light"> 
<labelfor="light">Light</label> 
<inputtype="radio"id="dark"name="theme"value="Dark"> 
<labelfor="dark">Dark</label> 

Submit
Displays a submit button for submitting all values from an HTML form to a form-handler, typically a server. The form-handler is specified in the form’s "action" attribute:

<formaction="myserver.com"method="POST">
  …
<inputtype="submit"value="Submit" />
</form>

Text
Defines a basic single-line text field that a user can enter text into. 

<labelfor="fname">First name:</label> 
<inputtype="text"id="fname"name="fname"> 

Password
Defines a single-line text field whose value is obscured, suited for sensitive information like passwords.

<labelfor="pwd">Password:</label> 
<inputtype="password"id="pwd"name="pwd"> 

Date
Displays a control for entering a date with no time (year, month and day).

<labelfor="dob">Date of birth:</label>
<inputtype="date"id="dob"name="date of birth">

Datetime-local
Defines a control for entering a date and time, including the year, month and day, as well as the time in hours and minutes.

<labelfor="birthdaytime">Birthday (date and time):</label>
<inputtype="datetime-local"id="birthdaytime"name="birthdaytime">

Email
Defines a field for an email address. It’s similar to a plain text input, with the addition that it validates automatically when submitted to the server.

<labelfor="email">Enter your email:</label>
<inputtype="email"id="email"name="email">

File
Displays a control that lets the user select and upload a file from their computer. To define the types of files permissible you can use the "accept" attribute. Also, to enable multiple files to be selected, add the "multiple" attribute.

<labelfor="myfile">Select a file:</label>
<inputtype="file"id="myfile"name="myfile">

Hidden
Defines a control that is not displayed but whose value is still submitted to the server.

<inputtype="hidden"id="custId"name="custId"value="3487">

Image
Defines an image as a graphical submit button. You should use the “src” attribute to point to the location of your image file.

<inputtype="image"src="submit_img.png"alt="Submit"width="48"height="48">

Number
Defines a control for entering a number. You can use attributes to specify restrictions, such as min and max values allowed, number intervals or a default value.

<inputtype="number"id="quantity"name="quantity"min="1"max="5">

Range
Displays a range widget for specifying a number between two values. The precise value, however, is not considered important. This is typically represented using a slider or dial control. To define the range of acceptable values, use the “min” and “max” properties.

<labelfor="volume">Volume:</label>
<inputtype="range"id="volume"name="volume"min="0"max="10">

Reset
Displays a button that resets the contents of the form to their default values.

<inputtype="reset">

Search
Defines a text field for entering a search query. These are functionally identical to text inputs, but may be styled differently depending on the browser.

<labelfor="gsearch">Search in Google:</label>
<inputtype="search"id="gsearch"name="gsearch">

Time
Displays a control for entering a time value in hours and minutes, with no time zone.

<labelfor="appt">Select a time:</label>
<inputtype="time"id="appt"name="appt">

Tel
Defines a control for entering a telephone number. Browsers that do not support “tel” fall back to standard text input. You can optionally use the "pattern" field to perform validation.

<labelfor="phone">Enter your phone number:</label>
<inputtype="tel"id="phone"name="phone"pattern="[+]{1}[0-9]{11,14}">

Url
Displays a field for entering a text URL. It works similar to a text input, but performs automatic validation before being submitted to the server.

<labelfor="homepage">Add your homepage:</label>
<inputtype="url"id="homepage"name="homepage">

Week
Defines a control for entering a date consisting of a week-year number and a year, with no time zone. Keep in mind that this is a newer type that is not supported by all the browsers.

<labelfor="week">Select a week:</label>
<inputtype="week"id="week"name="week">

Month
Displays a control for entering a month and year, with no time zone. Keep in mind that this is a newer type that is not supported by all the browsers.

<labelfor="bdaymonth">Birthday (month and year):</label>
<inputtype="month"id="bdaymonth"name="bdaymonth" min="1930-01" value="2000-01">

Visual Studio Code on Coursera

In addition to having Visual Studio Code installed on your own computer, in this course and throughout this program, you'll have the opportunity to work in Visual Studio Code right here on Coursera!   

As you progress through the course, you'll be able to write code in hands-on activities called Labs.  In these labs you'll be able to open Visual Studio Code and start writing code without ever leaving the course.


How to get started working on Labs

The Labs contain instructions explaining the coding task.


When you click the button to open the lab, a new tab will open with Visual Studio Code already setup and ready for you to start writing code!


You'll see all the files for the lab in the Project folder in the left sidebar.


And the large editor area where you write your code for the lab.


All Lab exercises will include two important files.  A README.md file which contains instructions for using Visual Studio Code and most importantly, how to run and view the output of your code.  The README.md file is the same for every Lab. There will also be an instructions.md file which provides specific instructions for each Lab.  

These files may looking a little confusing at first.  They're written using a language called Markdown.  Markdown is just used to add formatting to text elements.  Don't worry, you don't have to know anything about Markdown.  If you open these files in Preview you'll just see the formatted output and they'll look totally normal.

You'll also likely see quite a few files and folders when you open in the Lab.  Many of the files and folders you'll be able to ignore.  To get started, look at the instructions.md file and it will explain which file or files you'll be working in.

Working in the Terminal
For Labs in some courses, you may need to use a tool called the Terminal from time to time to complete course activities. You can open this by selecting the Terminal option in the upper Visual Studio Code toolbar.


How to download files from your Visual Studio Code Lab to your local device
1. Select the Lab Files button in your Lab Toolbar. 

2. You'll be able to download your full workspace, specific folders, or individual files through the checkbox selection tool. 

3. After you've selected these files, use the Download link to download your files to your local device. 


How to upload local files to your Visual Studio Code Lab
If you'd like to upload your course files from your local device to your Visual Studio Code lab, drag and drop your file from your local device into the Visual Studio Code file tree.


How to get a fresh copy of course-provided starter files
Your work will be saved and persist within your Visual Studio Code lab while you are enrolled in the course. If you'd like to get a fresh copy of the original instructor-provided files at any time, you can do this through the Lab Help option in your Lab Toolbar.  Don't worry - your original work and files will still remain in your lab until you personally remove or delete them, even when refreshing your files through the steps below.

1. First rename your original files to something like [yourfilename] [original].[your file extension]`. You can do this by right-clicking on your file in the Visual Studio Code file tree, selecting Rename, and providing a new file name.

  For example for index.html, this could be renamed to `index [original].html`

2. Select Lab Help from your Lab Toolbar and then select Get latest version. 


3. You should now see a fresh copy of the original instructor-provided files in your lab, in addition to your own  (renamed) files.

Create and test a form (solution)

The following code is an example solution for the previous exercise.

This code is placed inside the <main> element of index.html.

<form>
    <div>
        <label for="username">Username</label>
        <input type="text" id="username" required minlength="2">
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" id="password" required minlength="2">
    </div>
    <button type="submit">Log In</button>
</form>

While reviewing the code, note the following items:
  • The label for attribute value matches the value of the id attribute on the corresponding input element
  • The type attribute is set to text for the username input
  • The type attribute is set to password for the password input
  • Each field has a required attribute to enable client-side validation which checks that the form is filled out by the user
  • Each field has a minlength attribute with its value set to 2. This enables client-side validation which will prompt the user if the content of the field is less than 2 characters.
QUIZ 5 - Create and test a form


Cheat sheet: Interactive form elements

When filling in HTML forms, we expect users to abide by certain rules, like using numbers when asked to, or properly formatting a URL or an email when needed. However, humans are prone to errors and in some cases, they may overlook some of the data they input. That’s why it’s important to ensure the shape of the data we expect in each field is correct. HTML form validation is a set of attributes we can add to form inputs to perform automatic validation on the user’s behalf. 
The most important attributes you’ll find yourself using for validation are the following.

Required
Denotes a mandatory input that the user can’t leave empty. It can be used with any input type, like password, radio, text and so on. 

<input type="text" id="firstName" name="firstName" required>

Maxlength 
Specifies the maximum length of a text input, in other words, the maximum number of characters that can be entered for a specific field. If provided, it will prevent the user from entering more characters than the limit. 

<input type="text" id="description" name="description" maxlength="50">

Minlength 
Specifies the minimum length of a text input. If set, the input will not accept fewer characters than those specified. 

<input type="password" id="password" name="password" minlength="8">

Min and max attributes 
Determine the minimum and maximum values allowed for an input field. They are usually applied to numerical text inputs, range inputs or dates. 

<input type="number" id="quantity" name="quantity" min="1" max="10"> <input type="range" id="volume" name="volume" min="1" max="100">

Multiple 
Indicates that the user can enter more than one value in a single input field. This attribute can only be used for email and file input types. 

<input type="file" id="gallery" name="gallery" multiple>

Pattern 
Defines a particular pattern that an input field value has to fulfill to be considered valid. This attribute expects a regular expression to specify the pattern. It works with text, date, search, URL, tel, email and password input types. For example, you can restrict phone numbers to be only from the UK. 

<input type="tel" id="phone" name="phone" pattern=”^(?:0|\+?44)(?:\d\s?){9,10}$” >

QUIZ 6 - Declaring form elements


Submit

You have recently learned about how forms are sent to web servers and the difference between Get and Post. In this reading, you will build on this knowledge by learning about Submit. 

Action and method 

Form submissions are an essential part of the world wide web. Nearly every website uses forms, from buying items online to ordering food for delivery. When you click the login button on a website, it sends your username and password to a web server to log you into your account. 

As you know by now, you add a form to your web page using the form tag. 

<form> 
</form> 

But how the form is submitted is determined by two essential attributes: action and method. 

The action attribute specifies to which web address the form must be sent. This is address is location of server-side code that will process the request.

<formaction="/login"> 
</form>

It is important to note that action can be a full URL address such as https://meta.com, an absolute path such as /login, or a relative path such as login. 

The absolute path, which starts with a forward slash, will use the base address of the current website, such as https://meta.com and combine it with the absolute path. For example, if /login is the absolute path, the form will be submitted to https://meta.com/login. If the address is https://meta.com/company-info/ and /login is the absolute path, the submission address will still be https://meta.com/login.

Similarly, a relative path will combine the current web address with a relative path. For example, if the web browser is currently on the web page https://meta.com/company-info/, and the relative path is set to login, the form will be submitted to https://meta.com/company-info/login. 

The method attribute specifies which HTTP method is used to submit the form; GET or POST. 

<formmethod="get"> 
</form> 

<formmethod="post"> 
</form> 

The form will default to the HTTP GET method when the method attribute is not provided. 

As you may already know, when the form is submitted using the HTTP GET method, the data in the form's fields are encoded in the URL. And when the form is submitted using the HTTP POST method, the data is sent as part of the HTTP request body. 

When the web server receives the request, it processes the data and sends back an HTTP response. The response indicates the result of the submission, which can be successful or fail due to invalid or incorrect data. 

However, as a front-end developer, it is essential to know that forms are not the only way to submit data to the web server. As you learn more about JavaScript and front-end libraries, you’ll discover that developers often submit HTTP requests directly via code and send data as part of the HTTP request body in a text format called JavaScript Object Notation, or JSON. But that is a topic for another course. 

For now, practice building HTML forms and submitting data to the web server using the different attributes available. 

 QUIZ 7 - Form submission



Glossary: HTML form elements

The <form> element in HTML is an important and useful element. The following sheet provides an overview of the <form> constituent elements and their common attributes with simple examples for quick reference.

<input> 
It is used to create interactive controls, for example, buttons and various types of text fields and so on, to accept input or data from the user. The key attribute of this element is type. Some common values for the type include: button, checkbox, date, email, number, password, submit, text, and url. These values dictate the appearance of the element. For example, this code:

<form action="my_action_page"> 

  <label for="uname">Username:</label> 
  <br> 
  <input type="text" id="uname" name="username"> 
  <br> 
  <label for="pwd">Password:</label> 
  <br> 
  <input type="password" id="pwd" name="pwd"> 
  <br><br> 
  <input type="submit" value="Login"> 
</form> 

Results in the following output:


Two input types, text and password, as it displays in the browser.

 Note how the type password hides the user input. 

<label>
Defines a label for an element. It has an attribute "for", the value of which should be equal to the id attribute of the element it is associated with. Note how in the example above, the <label> is associated with the <input> using its id value. 

<select>
Defines a drop-down list of options presented to the user. It has a couple of attributes: 
  • Form, the id of the form in which the drop-down appears 
  • Name specifies the name of the control 
  • Multiple Boolean attribute, when specified, indicates if a user can select multiple options out of the list 
  • Required indicates if the user is required to select an option before submitting a form 
  • Size mentions the number of visible options in a drop-down list 
The options in a drop-down list are defined using the <option> element inside <select>. Note the example in the <option> description below. 

<textarea>
Defines a multi-line input field, typically to allow the user to input longer textual data. The common attributes for this element include: 
  • cols defines the width of the text area, the default value is 20 
  • form the form element the text area is associated with 
  • maxlength when specified, limits the maximum number of characters that can be entered in the text area 
  • minlength the minimum number of characters that the user should enter 
  • readonly once set, the user cannot modify the contents 
  • rows defines the number of visible text lines for the text area 
The following line of code defines a text area of 10 visible lines and nearly 30 characters wide where the user can input a maximum of 200 characters: 

<textarea name="response" rows="10" cols="30" maxlength=200> 

</textarea> 

<button>
Defines a clickable button. The onclick attribute defines the behavior when the button is clicked by the user. For example, in the code below, an alert message is shown to the user. 

<button type="button" onclick="alert('You just clicked!')">Click Me! 
</button> 

<fieldset> 
Used to group related input elements in a form. For instance, elements related to the user’s personal information and educational qualification can be grouped separately in two field sets. 

<legend> 
Defines a caption for the <fieldset> element. For example: 

<fieldset> 
  <legend>Personal Info</legend> 
  <label for="fname">First name:</label><br> 
  <input type="text" id="fname" name="fname" value="John"><br> 
  <label for="lname">Last name:</label><br> 
  <input type="text" id="lname" name="lname" value="Doe"><br> 
</fieldset> 

<fieldset> 
  <legend>Qualificaiton</legend> 
  <label for="pdegree">Primary degree:</label><br> 
  <input type="text" id="pdegree" name="degree" value="Masters"><br> 
  <label for="fos">Last name:</label><br> 
  <input type="text" id="fos" name="field" value="Psychology"><br> 
</fieldset> 

<datalist>
Specifies a list of pre-defined options for an input element. It differs from <select> since the user can still provide textual or numeric input other than the listed options. 
 
<form action="/my_action_page"> 
  <label for="flowers">Favourite flower:</label><br> 
  <input list="flowers" name="flowers"> 
  <datalist id="flowers"> 
    <option value="Rose"> 
    <option value="Lily"> 
    <option value="Tulip"> 
    <option value="Daffodil"> 
    <option value="Orchid"> 
  </datalist> 
  ... 
</form>


<output> 
Represents the result of a calculation (typically the output of a script) or the outcome of the user action. 

<option> 
Defines an option for the drop-down list. The following code example demonstrates how a simple list can be defined, with the rendered view below the code block. 

<label for="course">Choose a course:</label><br> 
<select id="course" name="courselist"> 
  <option value="html">HTML Introduction</option> 
  <option value="css">Styling with CSS</option> 
  <option value="js">JavaScript</option> 
  <option value="react">React Basics</option> 
</select> 


By default, the first item in the drop-down list is selected. To define a pre-selected option, add the selected attribute to the option. 

<optgroup> 
Defines a group of related options in a drop-down list. Its attribute label names the group. 

QUIZ 8 - Create a complex form


QUIZ 9 - User input and forms


Additional resources

The following resources will be helpful as additional references in dealing with different concepts related to the topics you have covered in this section.

Client-side validation of forms with HTML5
<input> tag in HTML
Form validation examples
Input type: Radio buttons
Why does your website look different in different browsers?
HTML Form submission – sending form data

Images

This lesson will help refresh your knowledge of the <img> tag and how you can use it to embed images in webpages. 

The <img> tag is used to add an image to a web page. The image’s address is specified using the src attribute. For example, if you wanted to embed an image file named photo.png, you can do that with the following HTML. 

<img src="photo.png">

You can also specify the width and height of the image using the width and height attributes. For example, if the width of the photo is 640 pixels and the height of the photo is 480 pixels, you can use the following HTML. 

<img src="photo.png" width="640" height="480">

It is important to note that you can set the image to a larger or smaller size and the web browser will automatically scale the image. For example, you can update the previous HTML to half the width and height and the image would shrink by 50%. 

<img src="photo.png" width="320" height="240">  

One useful feature of rendering images in the web browser is that the web browser can automatically keep the correct ratio of width to height. So for example, if you want to scale the image by 50%, you can simply set the width attribute and the web browser will automatically calculate the height. 

<img src="photo.png" width="320">

But what happens if the photo doesn’t load? Perhaps the file was accidentally deleted, or you mistyped the file name. Luckily, the web browser has a way to display some text when the image fails to load. This is done using the alt attribute. For example, you can display the text My Profile Photo using the alt attribute in the previous HTML. 

<img src="photo.png" width="320" alt="My Profile Photo">

It is important to ensure that screen reader accessibility software can interpret images displayed in the web browser. To support this, the <img> tag is combined with the <figure> and <figcaption> tags to provide a description of the image. The <img> tag is added inside the <figure> tag and the <figcaption> is specified after it. 

<figure> 
   <img src="photo.png" width="320" alt="My Profile Photo"> 
   <figcaption>A photo of myself on a beach in 2015</figcaption> 
</figure>

One last thing to note is that like videos and audio, the web browser only supports specific file types. These file types are: 
  • .APNG – Animated Portable Network Graphics 
  • .AVIF – AV1 Image Format 
  • .GIF – Graphics Interchange Format 
  • .JPEG / .JPG – Joint Photographic Expert Group image format 
  • .PNG – Portable Network Graphics 
  • .SVG – Scalable Vector Graphics 
  • .WEBP – Web Picture Format 
Images will be important as you build websites and ensuring they are accessible will provide a better user experience for all visitors. 

iFrame sandbox cheat sheet

The <iframe> is the inline frame element that embeds an HTML page into another page.  

Apart from the global attributes, which can be a part of the iframe, major element-specific attributes are listed below. 

allow 
It specifies what features or permissions are available to the frame, for instance, access to the microphone, camera, other APIs and so on. For example: 
  • allow="fullscreen” the fullscreen mode can be activated 
  • allow=“geolocation” lets you access the user’s location 
To specify more than one feature, a semicolon-separator should be used between features. For example, the following would allow using the camera and the microphone: 

<iframe src="https://example.com/…" allow="camera; microphone"> </iframe>

name 
The name for the <iframe>. For example: 

<iframe name = "My Frame" width="400" height="300"></iframe>

height 
It specifies the height of the frame. The default value is 150, in terms of CSS pixels. 
width 

width
Specifies the width of the frame, in terms of CSS pixels. The default value is 300 pixels.

referrerpolicy 
A referrer is the HTTP header that lets the page know who is loading it. This attribute indicates which referrer information to send when loading the frame resource. The common values are: 
  • no-referrer The referrer header will not be sent. 
  • origin The referrer will be limited to the origin of the referring page 
  • strict-origin The origin of the document is sent as the referrer only when using the same protocol security level (HTTPS to HTTPS) 
sandbox 
To enforce greater security, a sandbox applies extra restrictions to the content in the <iframe>. To lift particular restrictions, an attribute value (permission token) is used. The common permission tokens are listed below: 
  • allow-downloads Allows the user to download an item 
  • allow-forms Allows the user to submit forms 
  • allow-modals The resource can open modal windows 
  • allow-orientation-lock Lets the resource lock the screen orientation 
  • allow-popups Allows popups to open 
  • allow-presentation Allows a presentation session to start 
  • allow-scripts Lets the resource run scripts without creating popup windows 
Note that when the value of this attribute is empty, all restrictions are applied. To apply more than one permission, use a space-separated list. For example, the following would allow form submission and scripts while keeping other restrictions active: 

<iframe src="my_iframe_sandbox.html" sandbox="allow-forms allow-scripts"> 
</iframe> 

src 
The URL of the page to embed in the <iframe>. Using the value about:blank would embed an empty page. 

srcdoc
Let's you specify the inline HTML to embed in the <iframe>. When defined, this attribute would override the src attribute.  

For instance, the following code will display "My inline html" in the frame, instead of loading my_iframe_src.html. 

<iframe src="my_iframe_src.html" srcdoc="<p>My inline html</p>" > 
</iframe> 

loading
This attribute let's you specify if the iframe should be loaded immediately when the web page loads (eager) or loaded when iframe is displayed in the browser (lazy). This allows you to defer loading iframe content if it is further down your web page and outside of the display area when the page is initially loaded.

<iframe src="my_iframe_src.html" loading="lazy" > 
</iframe> 

title
This attribute let's you add a description to the iframe for accessibility purposes. The value of this attribute should accurately describe the iframe's content.

<iframe src="history.html" title="An embedded document about the history of my family" > 
</iframe> 

QUIZ 10 - Media elements


Additional resources



WEEK 2 - INTERACTIVE CSS

In this module, you will dive deeper into CSS by applying increasingly specific styling to various elements.

Understanding flexbox

Much like the div and box container that you can create using HTML, flexbox is a type of container. Flexbox can overcome the limitations caused by containers such as block and inline because it does a better job of scaling over larger web pages and also provides more dynamic control of the containers. This is because it can grow, shrink and align the items inside it which give better control to the programmer over the contents and styling of the items inside the container. 

Before learning about the common layouts built using the flexbox, it is important to understand the properties inside it and how flexbox works. Let’s examine some of the important characteristics of flexboxes and the properties that can be used to configure them.

Flexbox is single-dimensional, which means you can align it either along a row or a column and it is set to row alignment by default. There are two axes, the main and cross-axis, much like the x and y-axis used in coordinate geometry. When aligned along the row, the horizontal axis is called the main axis and the vertical axis is called the cross axis. For the items present inside the flexbox container, the placement starts from the top-left corner moving along the main or horizontal axis. When the row is filled, the items continue to the next row. Note that with the help of a property called flex-direction, you can instead flip the main axis to run vertically and the cross axis will then be horizontal. In such a case, the items will start from top left and move down along the vertical main axis. The properties you choose will help better control alignment, spacing, direction and eventually styling of the container and items present inside it. 

  


Let’s now examine some of the important properties that will allow you to configure a flexbox.

Flexbox properties
 Original HTML code:

<body>
  <div class="flex-container">
    <div class="box box1">  One..</div>
    <div class="box box2">  Two..</div>
    <div class="box box3">  Three..</div>
    <div class="box box4">  Four..</div>
    <div class="box box5">  Five..</div>
    <div class="box box6">  Six..</div>
    <div class="box box7">  Seven..</div>
  </div>
</body>

 Original CSS file: 

.box{
    background-color: aquamarine;
    border-radius: 5px;
    margin: 2px;
    padding: 10px;
}

Output:


There are seven div containers inside the HTML file.

The corresponding CSS file contains rules for all seven div tags that have the box class. Note how two class names are given for each of the tags, one that is common among all classes and another independent of it. The style is applied to all the containers. 

Now let’s add properties to the flex container by converting it into flex. 

display: flex;

.flex-container{
    display: flex;
}

The output is now seven flex containers that run from left to right starting in the top left corner.

Alignment properties
 Let’s examine a few alignment properties inside the flex. There are four main properties used to align a flex container and items present inside it:  
  • justify-content. For item alignment on main axis.
  • align-items. For item alignment on cross axis.
  • align-self. For unique flex items on cross axis.
  • align-content. Used for packing flex lines and control over space.
Of these, justify-content and align-items are frequently used for the respective two axes. 

Let’s first examine the use of justify-content which has a value of ‘left’ by default.

justify-content
CSS:

.flex-container{
    display: flex;
    justify-content: center
}

Output:

flex-wrap:
The default for this property is ‘nowrap’ which means the items will span the entire width of the axis. 

.flex-container{
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
}

Output:
The items will now be wrapped to the size of the available viewport. 

flex-direction: 
This property is used to set the main axis, which is a ‘row’ by default. It basically means you are changing your ‘main’ axis from horizontal rows to vertical columns. 

CSS Code:

.flex-container{
    display: flex;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
}

  Output:

The output looks like the original output; however, it is now actually a flex.

 Now let’s align the items again and examine a couple of the other properties mentioned earlier.   

align-items:
The alignment on the cross-axis is done with the help of this property. Let’s change the value for it to ‘flex-end’. 

CSS Code:

.flex-container{
    display: flex;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
    align-items:flex-end;
}

 Output:
The term ‘end’ refers to the right side of the page as the left side is seen as the beginning. 

align-self:
This property can be used on individual items inside the flex. 

.flex-container{
    display: flex;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
    align-items:flex-end;
}
.box3{
    background-color: blanchedalmond;
    align-self: center;
}

 Output:       
 

Here the color and alignment of the third box have been changed and it overrides the properties set using align-items.     

gap:
gap property can be used to create space between the items along the main axis. You can also individually configure the gaps in rows and columns using row-gap and column-gap properties.   

CSS Code:

.flex-container{
    display: flex;
    justify-content: center;
    flex-direction: column;
    flex-wrap: wrap;
    align-items:flex-end;
    gap:10px;
}
.box3{
    background-color: blanchedalmond;
    align-self: center;
}

 Output:


There is a clear change in spacing between the items. 

The final set of properties are flex-grow, flex-shrink and flex-basis. Together these determine how the flex takes up space, grows or shrinks according to the space available.

These are the sub-properties of a property called flex. Together all three properties can also be given values with the help of something called the shorthand notation in CSS. Shorthand notation helps you make your code compact and also easy to write and follow. The values left empty in shorthand notation are given their default values. 

For example:

.flex-container{
flex: 0 1 auto;
}

Here for the flex-container class, there is a set rule for the flex property. The values correspond to the three properties, namely the flex-grow set to 0, flex-shrink to 1 and flex-basis to auto. The flex-basis sets the initial size of the container. and together they define the rigidity or flexibility and dynamism you want to add to the flexbox. 

To demonstrate the effect of this, the code has to be modified slightly by removing the flex-direction value set to ‘column’. This will change it to default ‘row’ and the output will again be centrally aligned and horizontal best-distributed between two rows. 

Output:
The rest of the remaining code is unchanged. However, the output will change if the code is modified with the addition of the flex property inside the flex item box3 class. 

CSS Code
:
.box3{
    background-color: blanchedalmond;
    align-self: center;
    flex: 1 1 auto;
}

 Output:

The third box now takes up the entire free space available because flex-growth’s value has been set to 1. So if we have flex-grow set to 1, the children will all set to equal size. And if one of the children has a value of 1.5, that child would take up more space as compared to the others.

It’s important to understand how the changes in the main and cross axis affect the way you imagine and manipulate the flexbox. Once you’ve had more practice you’ll be more comfortable with the use of these properties, and it will become easier to use flexboxes and understand the flow and alignment of items inside the flexbox. 

CSS units of measurement

A web page, as you know it, is two-dimensional. In other words, it has width and height. There are a number of other ways you can express this such as vertical and horizontal, length and breadth, x and y axis and so on. Another property of a web page is its size which can either be static or dynamic. When you’ve encountered enough CSS code, you will note a number of different ways in which the values for the same property can be declared using different units of measurement. Most of these units of measurement are used to account for the dynamism and dimensionality of a web page. 

Let’s examine the most widely used units of measurement. They can broadly be categorized as Absolute and Relative units. 

Absolute units
Absolute units are constant across different devices and have a fixed size. They are useful for activities like printing a page. They are not so suitable when it comes to the wide variety of devices in use today that have different viewport sizes. Because of this, absolute units are used when the size of the web page is known and will remain constant. 

The table for absolute units can be seen below:

Unit

Name

Comparison

Q

Quarter-millimeters

1Q = 1/40th of 1cm

mm

Millimeters

1mm = 1/10th of 1cm

cm

Centimeters

1cm = 37.8px = 25.2/64in

in

Inches

1in = 2.54cm = 96px

pc

Picas

1pc = 1/6th of 1in

pt

Points

1pt = 1/72nd of 1in

px

Pixels

1px = 1/96th of 1in

Of these, the pixels and centimeters are most frequently used for defining properties. 

Relative values
When you create a web page, you will almost never have only a single element present inside it. Even in case of containers such as flexboxes and grids, there’s usually more than one element present that rules are applied to. Relative values are defined ‘in relation’ to the other elements present inside the parent element. Additionally, they are defined ‘in relation’ to the viewport or the size of the visible web page. Given the dynamic nature of web pages today and the variable size of devices in use, relative units are the go-to option in many cases. Below is a list of some of the important relative units. 

Unit

Description and relativity

em

Font size of the parent where present.

ex

x-co-ordinate or height of the font element.

ch

Width of the font character.

rem

Font size of the root element.

lh

Value computed for line height of parent element. 

rlh

Value computed for line height of root element which is <html>. 

vw

1% of the viewport width.

vh

1% of the viewport height.

vmin

1% of the smaller dimension of viewport.

vmax

1% of the larger dimension of viewport.

%

Denotes a percentage value in relation to its parent element. 

Many of these units are used in terms of the relative size of fonts. Some units are more suitable depending on the relative context. Like when the dimensions of the viewport are important, it's more appropriate to use vw and vh. In a broader context, the relative units you will see most frequently used are percentage, em, vh, vw and rem. 

Much like the absolute and relative units discussed above, certain properties have their own set of acceptable values that need to be taken into account. For example, color-based properties such as backgroundcolor will have values such as hexadecimal, rgb(), rgba(), hsl(), hsla() and so on. Each property should be explored on an individual basis and practicing with the code will help you to decide which of these units of measurement are the most suitable choice. 

Grids and flexbox cheat sheet

Note: ‘|’ stands for alternatives or OR.

Grid 
The syntax for creating a grid:

selector{
    display: grid/* or inline-grid */
}

Grid shorthand consists of the following properties with default values:

grid

A grid will allow you organize the various elements on your page. 

grid-template-rows: none

This feature allows you configure your elements so that they are organized similarly to rows on a table. 

grid-template-columns: none

This feature allows you configure your elements but with this setting the elements are organized like columns on a table. 

grid-template-areas: none

This feature allows you configure the names of a grid and how they sit in relation to one another. 

grid-auto-rows: auto

Default setting for all row sizes that have not been explicitly configured. 

grid-auto-columns: auto

Default setting for all column sizes that have not been explicitly configured. 

grid-auto-flow: row

Default location for rows that are not explicitly allocated. 

column-gap: normal

This sets the gap between the columns

row-gap: normal

This sets the gap between the rows

Grid properties for container

grid-template-columns: measurement units | % units |repeat()

Defines the line names, and maintains a constant size of column items. Can accept a range of different measurement sizes.

grid-template-rows: measurement units | % units |repeat()

Defines the line names, and maintains a constant size of rows. Can accept a range of different measurement sizes.

grid-auto-columns: measurement unit (fixed value for all columns)

Determines the default size for columns that have not been explicitly configured. 

grid-auto-rows: measurement unit (fixed value for all rows)

Determines the default size for rows that have not been explicitly configured.

grid-template: “header header” auto

This allows you define and maintain named cells on a grid 

“main right” 75vh

This defines two cells named main and right, that have a sizing of 75% of the viewport height. 

“footer footer” 20rem

This defines two cells named footer and footer, that have a sizing of 20 root em (rem). This defines the size in relation to the html font size. 

Gap

grid-gap: measurement units 

Determines the gap between rows and columns 

grid-column-gap: measurement units

Determines the gap between columns

grid-row-gap: m-unit-1 m-unit-2

Determines the gap between columns

Alignment

justify-items: start | center | end | stretch

Defines the default space that is allot to each item on the grid 

align-items: start | center | end | stretch

Defines the default space related to an item along the grid’s block axis  

place-items: start | stretch /* shorthand for two properties above */

This feature allows you align items with  the block and inline directions.

Justification

justify-content: start | center | end | stretch | space-between | space-evenly | space-around

Defines browser allocation of space to content items in relation to the main-axis 

align-content: start | center | end | stretch | space-between | space-evenly | space-around

Defines browser allocation of space to content items in relation to cross axis and block axis  

place-content: center | start

This feature allows you align items with  the block and inline directions.

Positioning

grid-auto-flow: row | column | dense

This relates to how the items are placed automatically within the grid

grid-auto-columns: measurement units

This relates to the size for columns created without specific size specifications 

grid-auto-rows: measurement units

This relates to the size for rows created without specific size specifications 

Grid properties for items (child)

grid-column: column position /* E.g. 1/2 */

Allows for specifying where on the grid the column is to start. 

grid-column-start: column start position

This property determines the starting column position an item is placed on a grid. 

grid-column-end: column end position

This property determines the end column position an item is placed on a grid. 

grid-row: row position /* E.g. 1/2 */

Allows for specifying where on the grid the row is to start. 

grid-row-start: row start position

This property determines the starting row position an item is placed on a grid. 

grid-row-end: row end position

This property determines the end row position an item is placed on a grid. 

Justification and alignment

justify-self: start | center | end | stretch

Determines how  an item is positioned inside its aligned container in relation to the appropriate axis. 

align-self: start | center | end | stretch

Aligns an item within a grid area. 

place-self: start | stretch /* shorthand for two properties above */

This setting lets one align and justify an item within a block. 

Flexbox

The syntax for creating a flexbox:

selector{
    display: flex | inline-flex
}

Here the selector can refer to any of the following flex attributes 
  • Attribute selector
  • Class Selector
  • ID Selector 
  • Type Selectors 
  • Universal Selectors 
The display relates to how you want the selector to be shown. Setting display to flex makes the given selector a flex box. Setting display toinline-flex makes the selector a flex box container while will be inline. 

Properties for flexbox container

flex-direction: row | row-reverse | column | column-reverse

It is possible to specify the direction your elements will follow. Traditionally text goes from left to right which is flex’s default setting however it can be set from right to left or even top to bottom. The four flex-direction are:
  • row : organized from left to right 
  • row-reverse: organized from right to left 
  • column: organized from top to bottom
  • column-reverse: organized from bottom to top. 
flex-wrap: wrap | nowrap

The standard layout is to plot the elements from left to right in a straight line. The wrap feature allows you customize this to match the size of the window displaying the page. 
  • wrap: Automatically wrap the items with as the window space gets smaller. 
  • Nowrap: Default setting, items remain rigid and don’t respond  to adjustments made to the window size.
align-items: flex-start | flex-end | center |Stretch

This determines how the flex items are to be positioned on the page. Items can be aligned in a variety of ways 

Flex-start: Similar to standard writing, items start at the top left-hand corner and are positioned from left to right 
  • Flex-end: Position begins in the bottom right hand corner. 
  • Center: Item is positioned from the center. 
  • Stretch: item expands to fill the container. 
justify-content: flex-start | flex-end | center | space-between | space-evenly


Justify-content determines the alignment of the flex items. 
  • Flex-start: goes from right to left along the main axis. 
  • Flex-end: goes from left to right along the main axis. 
  • Center: Starting at the middle, alignments expands from there. 
  • Space-between: first and last item are flush with the left and right wall respectively, every other item is evenly spaced.
  • Space-evenly: each item is equidistant from each other and the boundary wall 
Properties for flexbox items (child)

flex-grow: factor of flex’s main size   

This attribute enables the flex container to grow proportionally to the other containers present. 

flex-shrink: factor of flex’s main size

This allows elements to shrink in relation to items around it.

flex-basis: auto | factor of main’s size | measurement unit

The sets the initial main size of an item. It can be overridden if other stylized elements are configured. 

order:position in flex /* Set ascending by default */

The standard positioning of items is by source order, however this feature will enable you to configure where the items appear on the page. 

align-self: start | center | end | stretch

This determines where on the page the child items will be positioned. Similar to the main flex attributes, start is to the left and end is to the right.

Grid template area

Grid areas are a way to group one or more grid cells. The grid template area is an extension of this concept where you can give names to these grid areas. Once you have the names defined, you can address these new grid area items by their names and configure them accordingly. 

The property grid-template-areas is usually placed inside the body tag or any container where the grid needs to be placed, the same way that you would define the rules for the grid. The main difference is, in case of grid-template-areas the values present will be the different names. 

Process
The process isn’t prescriptive but these are the steps in general:
  • Define the grid using display property 
  • Set the height and width of the grid 
  • Set the grid-template-areas with the appropriate name identifiers
  • Add the appropriate sizes for the rows inside the grid using grid-template-rows property 
  • Add the appropriate sizes for the columns inside the grid using grid-template-columns property 
But how exactly do you use these names and where do they come from? The names that you use inside the grid template areas are the HTML tags that you have used. Or, where you need to get more specific, you designate a class name to these tags. Once the names are assigned, you define the properties for each class the same way that you define them conventionally. Let's examine an example.

Example

HTML Code:

<head> 

    <link rel="stylesheet" href="gridta.css"> 

</head> 

 

<body> 

    <header> Header </header> 

    <nav class="nav-bar"> Navigation </nav> 

    <main> Main area </main> 

    <footer> Footer </footer> 

</body> 

CSS Code

body { 

    display: grid

    height: 200px

    grid-template-areas: "head head" 

                         "nav  main" 

                         "footer  footer"

    grid-template-rows: 30px 1fr 30px

    grid-template-columns: 150px 1fr

  } 

   

  header { 

    grid-area: head

    background-color: lightsalmon

  } 

   

  .nav-bar { 

    grid-area: nav

    background-color: lightblue

  } 

   

  main { 

    grid-area: main

    background-color: lightyellow

  } 

   

   footer { 

    grid-area: footer

    background-color: firebrick

  } 

Output:   


Grid-based output presenting "header, navigation, main area, and footer."
Though there are five sets of rules, logically the CSS code is divided into two sections. The first is where you define the rules for the grid inside the body selector. And second is where you allocate specific rules for the different grid areas. The way these grid areas are distributed is according to how you have defined the names inside the grid-template-areas property. In the example above the relevant code is: 

 grid-template-areas: "head head"
                         "nav  main"
                         "footer  footer";

The ‘head’ is written twice to imply two columns and the rest of the content follows the usual convention. The number of rows will be the number of ‘pairs of quotes’ you have used which in this case is three. Namely  “head head”, “nav main” and “footer footer”. Once you know the number of rows and columns, the values for those will be set by grid-template-rows and grid-template-columns. Since these are three and two respectively here, you need to add that many values. The height simply gives the overall value of the height for the grid. 

Note that the number of times you wrote “header” did not have to be two. You could write more of those and if you align the rest of the grid-names correctly, the height and width of the grid-areas will be distributed proportionately. 

Let’s return to the example. If you keep all other properties the same but you change the grid-template-areas as follows: 

grid-template-areas: "head head head"
                         "nav  main main"
                         "footer  footer footer";

The output will remain the same as you have fixed the value of the third row to “30px”. The example is simple for the sake of clarity, but if you had used relative values, you would’ve seen an observable change in the comparable sizes of nav and main grid-areas. 

Grid-areas are convenient when you have a clear schematic of what you want in a grid. It’s also easier to configure individual areas if you can address them by their names. Let’s say you are designing a resume on your website, you will be able to name the different areas such as ‘Bio’, ‘Education’, ‘Work experience’ and so on. And it’s easier to use these labels when you are defining the rules. Creating a block diagram using pen and paper before starting to work on a grid is always a good idea. 

QUIZ 1 - Creating layouts


Additional resources

Here is a list of resources about layouts, flexboxes, grids and viewports in HTML and CSS that 
may be helpful as you continue your learning journey.
All selectors and their specificity

As you build a website, the complexity of the code might increase to such a point that more than one CSS rule is applied to the same element. Or, you might accidentally add more than one rule over the same element. This results in conflicts as only one rule can be applied to a specific property. For example, the color of a certain p tag can either be blue or white, but not both. CSS engines use something called specificity to resolve these conflicts. Specificity is the ranking or score that helps CSS determine the final rule that will be applied to a given element. 

This reading will help you grasp how the element with the ‘highest’ specificity is selected by CSS. But before you read on, it is important to note that these rules only apply in cases where conflicts arise for the properties. 

Specificity hierarchy
CSS has a set of rules that it uses to ‘score’ or assign a certain weight to selectors and this creates a specificity hierarchy. Based on the weights, there are four categories in this hierarchy: 
  • Inline styles 
  • IDs 
  • Classes, attributes, and pseudo-classes 
  • Elements and pseudo-elements 
Inline styles
Inline styles are attached to the elements within your HTML code like with the ‘style’ attribute. inline styles have the highest specificity. That means that rules that are defined as inline styles will be applied irrespective of other rules. 

For example, take these two rules that create a conflict in color styling for a p tag:

 <p style=“color: white;”> 
p{color: blue

The p tag will be colored white because it is declared inside the inline tag. 

IDs

Next in the hierarchy are IDs and by now you know that they are represented by ‘#’.  For example:

#div

Classes, attributes, and pseudo-classes
Classes, and the attributes inside the selectors, come next with what is called the pseudo-classes that you will soon learn more about. 

For example:

.my-class 

p[“attribute”]

div:hover

Elements and pseudo-elements
Finally, elements and something you call pseudo-elements have the lowest position in the specificity hierarchy. You will learn more about pseudo-elements later in this lesson.

Calculating scores
But by now you might wonder how is specificity calculated? 

CSS uses the hierarchical model internally to calculate the specificity of the selectors used on a web page. But often as the size of CSS code increases, developers unavoidably face rule conflicts. In these cases, developers use the specificity hierarchy to calculate the precedence of CSS rules and to control the outcome of their web pages. 

Let’s explore a practical example of how to determine the score of a few selectors. 

#hello {} will be 0100

div {} will be 0001 and

div p.foo {} will be 0012

In the order stated above, the four categories will be assigned values 1000, 100, 10 and 1 with the element selectors having the lowest value of 1. These scores will be calculated respectively for each element present inside the selector. The total score for these elements is then calculated and the one with the highest value has the highest specificity.

Let’s explore a couple of examples for clarity. Take note that the properties and values are not included in these examples to keep the focus on the selectors only. 

Example 1

p {} 
div p {}
div p.foo {}

p  => 1 element =>  0 0 0 1 => Score: 1

div p => 2 elements => 0 0 0 2 => Score: 2

div p.foo {} => 2 elements and 1 class selector => 0 0 1 2 => Score: 12

The third case has a total of 12 for the p tag and so has the highest specificity. The rules for the other two cases are then overridden and the rules inside the third case are applied. 

Example 2

p#bar => 1 element & 1 ID =>  0 1 0 1 => Score: 101

p.foo => 1 element & 1 class => 0 0 1 1 => Score: 11

p.p.foo => 1 element & 2 class =>  0 0 2 1 => Score: 21

By now it should be clear that the case containing ID has a much higher score and the rules inside it will be applied. 

Once you learn about the different pseudo-classes, pseudo-elements, and wide range of selectors later in this section, it will be easy to see why understanding specificity is important. 

While the weights assigned from the hierarchical structure help in a systematic approach, there are a few more guidelines and rules that become important especially in cases when the score for the different selectors is the same. Some of these are:
  • Every selector will have a score and place in the hierarchy
  • In the case of selectors with equal specificity, the latest or last written rule is the one that will be applied
  • In general, ID selector should be applied in cases where you need to be certain about a rule 
  • Universal selectors have zero specificity value
This reading only gave you an overview of specificity, but you should know that it is a much broader topic and also the underlying basis on which CSS engines work. That's what the 'Cascading' in CSS means: the way in which CSS engines evaluate and apply the specificity rules is called ‘cascade’. Cascade is a type of small waterfall that falls in stages down the rocks and that is exactly how CSS behaves. 

Don’t be too worried about applying what you’ve learned now, there are CSS specificity calculators available that can help you with determining the styling outcomes of your pages. 

Pseudo-elements

By now you know that pseudo-elements help you style a specific part of an element. For example, you can decide to apply styling to only the first word or line in a given element. First, let’s examine the syntax of a pseudo-element.

Syntax

selector::pseudo-element {

 property: value;

}


It is important to note that pseudo-elements use two colon characters instead of one.

Now, let’s explore some examples of popular pseudo-elements.

::first-letter

You can use first-letter to change the color of just the first letter of each of the three points in the example text.

HTML code:

<!DOCTYPE html> 

<html> 

    <head> 

        <link rel="stylesheet" href="pseudo4.css"> 

    </head> 

<body> 

    <ul> 

        <li>Based in Chicago, Illinois, Little Lemon is a family-owned 
Mediterranean restaurant, focused on traditional recipes served with a modern 
twist. </li> 

    <li>The chefs draw inspiration from Italian, Greek, and Turkish culture 
and have a menu of 12–15 items that they rotate seasonally. The restaurant 
has a rustic and relaxed atmosphere with moderate prices, making it a popular 
place for a meal any time of the day.</li> 

    <li>Little Lemon is owned by two Italian brothers, Mario and Adrian, 
who moved to the United States to pursue their shared dream of owning a 
restaurant. To craft the menu, Mario relies on family recipes and his 
experience as a chef in Italy.</li> 

  </ul> 

</body> 

</html> 

CSS Code:

li::first-letter { 

color:coral

font-size: 1.3em

font-weight: bold

line-height: 1


Output: 

Although the code only changed the first letter of each bullet point, it makes a big difference in terms of presentation. Now let’s change the font in a different way. 

::first-line
First-line will change the complete first line of each of the bullet points to light sea green. 

CSS code:

ul{
    list-style-type: none;
}

li::first-line {
    color: lightseagreen;
    text-decoration: underline;
    line-height: 1;
}

Output:

Because it’s only the first line of each bullet point, it almost functions like dividers between the three different points instead of having to rely on bullets.  

Note that the contents of the line to which this pseudo-element is applied will change as you increase or decrease the size of your viewport. 

Output:
::selection
Selection is another useful pseudo-element. For example, you may use it when you are taking notes on your device because it allows you to highlight specific text. The effect of it becomes obvious only after the user selects content. On web pages today, you will typically see inverted colors from white-black to black-white when selecting a portion of text.

CSS code:

ul{
    list-style-type: none;
}

li::selection {
    color:brown;
    background-color: antiquewhite;
    line-height: 1;
}

 Here is an example of a selection of text.

 Output:

And another example of the same text but with a different section selected and highlighted.

Output:

  Different segments of the text are highlighted depending on the text that is selected at any given point.    

::marker  
Markers are typically used to add style elements to a list, for instance, to color bullet points. For example, you can enhance the user experience when you use a marker in the following way.    

CSS code:

li::marker {
    color: cornflowerblue;
    content: '<> ';
    font-size: 1.1em;
}

Output


Now the bullet points are cornflower blue and they have the shape specified in the code.

::before and ::after
One more pair of pseudo-elements are the ::before and ::after pseudo-elements. They allow you to add content before and after an element on which they are allowed. In other words, new content can be added to a page without adding HTML code for it. You can also add styling options for this content. Let’s do an example where text is added both before and after some cooking guidelines to identify them as important tips. 

HTML code:

<body>
    <p id="tips"> Don't rinse your pasta after it is drained. </p>
    <p> Slice the tomatoes. Take the extra efforts to seed them. </p>
    <p id="tips"> Peel and seed large tomatoes. </p>
</body>

CSS code:

#tips::before{
    background: darkkhaki;
    color:darkslategray;
    content: "Tip:";
    padding-left: 3px;
    padding-right: 5px;
    border-radius: 10%;
}

#tips::after{
    background:darkkhaki;
    color:darkslategray;
    content: "!!";
    padding-right: 5px;
    border-radius: 20%;
}

Output:

The “content” property is where the text for the guidelines goes. The word “tip” has been added before each guideline thanks to the rules added for tips::before. And, each of the three guidelines now has two exclamation marks after them thanks to the rules added for tips::after. Note how the second <p> element inside the HTML code remains unaffected. You don’t have to use after and before together like this, but sometimes it is useful to combine them.

The examples covered here illustrate that adding simple code for pseudo-elements can greatly enhance the appearance of websites. There are plenty of other pseudo-elements and some of them are more popular than others. You can follow your own style and explore the creative possibilities that pseudo-classes and pseudo-elements offer.

CSS Pseudo cheat sheet

Simple selectors

Selector

Syntax

Example

Element

element

div {

}

Class

.class

.alpha { }

ID

#id

#alpha { }

Universal

*

* { }

Variations of simple selectors

Elements

Syntax

Example

Description

Two classes

.first-class.second-class

.alpha.beta { }

All elements with classes alpha and beta

Element and class

element.class

p.alpha { }

All alpha class elements inside <p>

Two elements

element, element

p, div { }

All <p> and <div> elements

Two elements

element element

p div { }

All <div> elements inside <p>

Descendant selectors/combinators

Selector

Syntax

Example

Description

Descendant

element element

div p { }

All <p> descendants of <div>

Child

element>element

div > p { }

All <p> direct descendants of <div>

Adjacent Sibling

element+element

div + p { }

<p> element directly after <div>

General Sibling

element~element

div ~ p { }

All <p> element iterations after <div>

Attribute selectors

Selector

Syntax

Example

[attribute]

[href] {

}

Selects all elements with a href attribute

[attribute=value]

[lang="fr"] {

}

Selects all elements with lang attribute that has a value of "fr"

[attribute~=value]

[input~=hello] {

}

Elements with input attribute containing the whitespace separated substring "hello"

[attribute|=value]

[lang|=en] {

}

Elements with lang attribute value equal to "en" or "en-"(en hyphen)

[attribute^=value]

a[href^="https"] {

}

Every <a> element with href attribute value begins with "https"

[attribute$=value]

a[href$=".docx"] {

}

Every <a> element with href attribute value ends with ".docx"

[attribute*=value]

a[href*="meta"] {

}

Every <a> element with href attribute value has substring "meta"

Pseudo-class

Example

Description of selection

:active

a:active { }

All active links 

:checked

input:checked { }

All the checked <input> elements

:default

input:default { }

All default <input> elements

:disabled

input:disabled { }

All disabled <input> elements

:empty

div:empty { }

All the <div> elements with no children

:enabled

input:enabled { }

All the enabled <input> elements

:first-child

p:first-child { }

All the <p> elements who are the first child of a parent element

:first-of-type

p:first-of-type { }

All the <p> element who are the first <p> element of a parent element

:focus

input:focus { }

Input element under focus

:fullscreen

:fullscreen { }

The element in full-screen mode

:hover

p:hover { }

Action effect on mouse hover

:invalid

input:invalid { }

Input elements with an invalid value

:last-child

p:last-child { }

All the <p> elements who are the last child of a parent element

:last-of-type

p:last-of-type { }

All the <p> elements who are the last <p> element of a parent element

:link

a:link { }

All unvisited links

:not(selector)

:not(div) { }

All the elements that are not a <div> element

:nth-child(n)

div:nth-child(3) { }

All the <p> elements that are the third child of a parent element

:nth-last-child(n)

div:nth-last-child(3) { }

All the <div> elements which are the third child of a parent element, counting from last child element

:nth-last-of-type(n)

p:nth-last-of-type(2) { }

The second sibling from the last child of a parent element.

:nth-of-type(n)

p:nth-of-type(2) { }

The second sibling of a parent element.

:only-of-type

p:only-of-type { }

All the <p> elements which are only <p> elements inside its parent

:only-child

p:only-child { }

All the <p> elements which are only child of a parent element

:optional

input:optional { }

The input elements with no "required" attribute

:required

input:required { }

Selects input elements with the "required" attribute specified

:root

:root { }

The Root element of document

::selection

::selection { }

The portion of an element that is selected by a user

:valid

input:valid { }

All the input elements with a valid value

:visited

a:visited { }

Selects all visited links

Pseudo-element selectors

Syntax

Example

Description

::after

p::after { }

Inserts content after content of <p> element

::before

p::before { }

Inserts content before content of <p> element

::first-letter

p::first-letter { }

Selects first letter of every <p> element

::first-line

p::first-line { }

Selects first line of every <p> element

::placeholder

input::placeholder { }

Selects input elements with "placeholder" attribute specified

::marker

::marker { }

Selects markers in a list

QUIZ 2 - CSS selectors


Additional resources

Here is a list of resources about selectors, pseudo-classes and pseudo-elements in HTML and CSS that may be helpful as you continue your learning journey.

Commonly used selectors
Combinator selectors
Comprehensive list of selectors
Comprehensive list of pseudo-classes
Comprehensive list of pseudo-elements

Text effects cheat sheet

The effects developers use on text items on a web page are chosen mainly because of their styling and layout style. Interesting effects can be created by combining these with other CSS properties. 

The visual representation of text content can be changed by four main properties: text-transform, font-style, font-weight and text-decoration.

Property 

Values

Description

Text-transform

None, uppercase, lowercase, capitalize, full-width

Modify text properties

Font-style

Normal, italic, oblique

Font styling options such as italics 

Font-weight

Normal, weight, lighter, bolder, 100-900

Other font styling options like change of emphasis such as making text bold

Text-decoration

None, underline, overline, line-through

Shorthand for auxiliary elements added to text using other properties such as text-decoration-line

The additional properties that help configure styling effects are below.

Text-align

For horizontal alignment of text

Text-align-last

Alignment for the last line when text set to justify

Text-combine-upright

Multiple characters into the space of a single character placed upright like in Mandarin

Text-decoration-color

Color configuration of the text-decoration

Text-decoration-line

Line type in text-decoration such as underline, overline and so on

Text-decoration-style

Styles added to lines under text such as wavy, dotted and so on

Text-decoration-thickness

Thickness of the decoration line

Text-emphasis

Shorthand for other properties such as color and style 

Text-indent

The indentation of the first line 

Text-justify

Specifies the justification method used when text-align is "justify"

Text-orientation

Orientation of text in a line such as sideways, upright and so on

Text-shadow

Adds shadow to text 

Text-underline-position

Declare position of underline set using the text-decoration property

Other than these, there are some more properties that help modify the alignment and define the scope of text with their containers. 

Property 

Values

Description

Text-overflow

Clip, ellipsis

Determines overflow behavior of text with the container

Word-wrap

Normal, anywhere, break-word

Applies to inline elements, alias for overflow-wrap

Word-break

Normal, break-all, keep-all, break-word

Used for long words to decide if words should break or overflow

Writing-mode

Horizontal-tb, vertical-lr, vertical-rl

Can set the text direction vertical or horizontal

The properties mentioned are ones that can be used for giving effects to text. 

CSS keyframes

In this reading, you will become acquainted with the @keyframes rule and you’ll learn how to use it with the animation property in CSS. The rules covered so far are for alignment and styling of web pages using CSS. Keyframes are a type of at-rule which are represented by the '@' suffix. At-rules are statements inside CSS that describe how to behave or perform certain actions. In line with that, keyframes are defined as '@keyframes' in the CSS code. @keyframes are part of the animation sequence and help in defining the steps inside it. Imagine an object on your web page moving from point A to point B. You can use the transition and transform properties to do that, but animation sequences are used to accomplish more complex behaviors in an easier way. 

from{} and to{} keywords and using percentages(%) syntax

@keyframes animation-name { 

from { 

property-a: value-a


 

to { 

property-a: value-b



The 'from' and 'to' keywords are used inside the @keyframes rule to mark the transition of one or more properties and can be seen as the start and end points of that transition. As can be seen from the syntax, the values of ‘property-a’ changes from ‘value-a’ to ‘value-b’. To expand on the use of ‘from’ and ‘to’, the @keyframes allows you to add more steps to your animation by using a percentage that represents the completion of the animation. 

@keyframes identifier { 

0% {transform: rotate(100deg);} 

30% {opacity: 1;} 

50% {opacity: 0.50;} 

70% {opacity: 1;} 

100% {transform: rotate(50deg);} 

The different percentages used in the example demonstrate the progression of the animation. Note that it doesn’t have to be the same property that you modify in these steps. That's not possible using the transition property, but you can do it with @keyframes. This flexibility is what makes @keyframes so powerful. Another advantage is how these animations can also loop infinitely, run forwards, reverse and alternate.

@keyframes are tied in with the animation-name to which they are going to be applied. To give an overview of the animation property, it consists of other sub-properties. Of these, animation-name and animation-duration must be defined while others such as timing-function, delay, direction, fill-more, iteration-count and so on can be added. 

Animation property shorthand:

The shorthand for the animation property consists of the following properties with their default values:
  • animation-name: none 
  • animation-duration: 0s 
  • animation-timing-function: ease 
  • animation-delay: 0s 
  • animation-iteration-count: 1 
  • animation-direction: normal 
  • animation-fill-mode: none 
  • animation-play-state: running 
  • animation-timeline: auto 
If the values of any of these are not defined, you should assume that they are the default. Of these, the first property of the animation-name is what's used to tie it to the @keyframes rule.

Let’s now examine an example of how you can use @keyframes and the animation property. 

Animation example

HTML code:

<body> 

<div class="box"></div> 

</body> 

</html> 

CSS code:

body

padding: 30px;} 

 

.box

background-color: lightcoral

width: 50px

height: 50px

animation: myanimation 3s infinite ease-in


 

@keyframes myanimation

from{width: 50px


 

to{width: 100px


In the example, the width of the object changes from 50 pixels to 100 pixels over a span of 3 seconds and loops infinitely afterward. 

This is a very simple example of how you can use the animation property with the help of @keyframes rule to create your desired animation.

If you modify this code and change the animation rules to percentages, it will have the same output.     

@keyframes myanimation{
0%{width: 50px;
}

100%{width: 100px;
}

Now, let’s add an intermediary step at 50%. 

@keyframes myanimation{
0%{width: 50px;
}

50%{background-color: aquamarine;
    height: 20px;
}

100%{width: 100px;
}

The output is drastically different now after adding just two lines of code. Just like this, you can keep adding steps inside your @keyframes rule to make it even more dynamic and add the desired animation effects. Animation property and @keyframes rule can be used in very creative ways to enhance a web page. 

Animation and effects cheat sheet

Transform property

Syntax
transform: transform function-values

Example

.sample-class {
    transform: rotate(60deg);
}

Keyword-value type: none


.sample-class {
    transform: none;
}

Function-value type: matrix() 

Variations: matrix(), matrix3d(

.sample-class {
     transform: matrix(1.02.03.04.05.06.0);
}

Function-value type: rotate(deg)

Variations: rotate(), rotate3d(), rotateX(), rotate(), rotateZ()

.sample-class {
    transform: rotate3d(3,2,1100deg);
}

Note: In rotate3d(), the respective values represent x, y, z co-ordinate and degree of rotations

Function-value type: translate(x,y)

Variations: translate(), translate3d(), translateX(), translateY(), translateZ()

.sample-class {
    transform: translate3d(10px20px30px);
}

Note: In translate3d(), the respective values represent translation along the x, y, z co-ordinates

Function-value type: scale(factor)

Variations: scale(), scale3d(), scaleX(), scaleY(), scaleZ()

.sample-class {
    transform: scale3d(210.3);
}

Note: In scale3d(), the respective values represent scaling times along the x, y, z co-ordinates

Function-value type: skew(deg, deg) 

Variations: skew(), skewX(), skewY()
 
.sample-class {
    transform: skew(100deg);
}

Global value types:

.sample-class {
    transform: inherit;
}

.sample-class {
    transform: initial;
}

.sample-class {
    transform: revert;
}

.sample-class {
    transform: revert-layer;
}

.sample-class {
    transform: unset;
}

Multiple transform over the same element

Syntax
Transform can be applied for rotate(), scale() and translate() that can be listed together. Each of these properties can have their own values and the actions will give a combined effect. 

Example 

.sample-class {
    transform: rotate(45deg) scale(1.5) translate(45px);
}

Additional property under transform:transform-origin

Determines the anchor point for the centering of transform.

Example 

.sample-class {
    transform-origin: 10px 10px;
}

.sample-class {
    transform-origin: right bottom;
}

Transition property

Transition shorthand 
Transition shorthand has four following sub-properties, each ofwhich can also be individually defined. transition-property
  • transition-duration
  • transition-timing-function
  • transition-delay
You have to list the values without naming them individually.

Values skipped will be assigned their default values. 

Syntax 
transition: property duration timing-function delay; 

Example 

transition: margin-left2s ease-in-out 0.5s; 

Animations and @keyframes 

animation property: 

Syntax 
animation: name duration timing-function delay iteration-count direction fill-mode play-state;

Example

.sample-class {
    animation: none 2 ease 0.5 4 normal none running;
}

The animation property is a shorthand for the sub-properties below:

animation-name
animation-duration
animation-timing-function
animation-delay
animation-iteration-count
animation-direction
animation-fill-mode
animation-play-state

The values not mentioned are given default values.

Animation-name property is used to tie-in the @keyframes rule.

@keyframes

Syntax

@keyframes mymove {
  from {property: value}
  to { property: value }
}

Example

@keyframes animation-name {
    from {bottom:0px;}
    to {bottom:100px;}
}

Percentage denotes the timing of the animation. 

Alternative syntax

@keyframes animation-name {
/* declare actions here */
}

Example

@keyframes animation-name {
    0%,100%{
        background-color: blue;
    }
    50% {
        background-color: green;
    }
}

Multiple animations

Works the same as regular animation, multiple rules can be set. 

#some-class{
    animation: animation-a 2s linear infinite alternate
        animation-b 3s ease infinite alternate;
}  

Preprocessors: sass, scss, Stylus

Preprocessors: sass, scss
Now that you have learned about different animation effects, let's explore the topic of preprocessors which can make the process of creating them easier. CSS preprocesses are special compilers used to create a CSS file that can be referenced by an HTML document. They are generally used to reduce the amount of CSS you need to write and allow you to re-use values across multiple rules. This will make re-using animations and effects much easier. And because preprocessors are an extension of CSS they'll help not just in animation but any CSS code. Let's learn a little more about them.

Preprocessors provide audit functionality on top of the CSS features already present. Some of the features of preprocessors include the option to create variables, loops, and if else statements. Different preprocessors each have their own syntax and configurations for adding these features. Some of the most commonly used preprocessors include Sass, LESS, Stylus and PostCSS. The use of these preprocessors requires the installation of a compiler on top of your web server. 

In the early days of CSS, the main problem developers faced was the difficulty of managing the code. The way CSS was designed made the code very long, messy and complex. It also made it difficult to troubleshoot. Preprocessors have their own scripting language that adds logical structures, automation properties, reusability and bloating of the code. You’ll now explore some of the different preprocessors available.

SASS and SCSS
Syntactically Awesome Style Sheets (SASS) is a scripting language that CSS compiles and interprets into CSS. SCSS, which stands for Sassy CSS is the syntax for SASS and can be seen as an advanced version of both SASS and CSS. The difference between SASS and SCSS is best explained by the SASS documentation, which states:

"There are two syntaxes available for Sass. The first, known as SCSS (Sassy CSS) and used throughout this reference, is an extension of the syntax of CSS. This means that every valid CSS stylesheet is a valid SCSS file with the same meaning. This syntax is enhanced with the Sass features described below. Files using this syntax have the .scss extension.

The second and older syntax, known as the indented syntax (or sometimes just “Sass”), provides a more concise way of writing CSS. It uses indentation rather than brackets to indicate the nesting of selectors and newlines rather than semicolons to separate properties. Files using this syntax have the .sass extension."

This example highlights these differences.

Regular CSS:

body { 
    font: 100% Arial
    color: lightblue

This is the SCSS: 

$font-stack: Arial
$primary-color: lightblue

body { 
  font: 100% $font-stack
  color: $primary-color

SASS for the same block:   

$font-stack: Arial 
$primary-color: lightblue 

body 
  font: 100% $font-stack 
  color: $primary-color 

The variables have been defined at the top with labels such as ‘$font-stack’ and ‘$primary-color’. This is done with the ‘$’ suffix. The result for both will be the same, and it is not hard to imagine how much time this can save for the developer in complex code blocks where there are a number of occurrences of ‘lightblue’ color. These variables are placed at the top of the SCSS page. 

In the case of SASS, the variation has mainly removed the curly brackets and semi-colons from the code. 

The nesting of selectors and separation of properties here is done by means of indentation. You should note that all this syntax is valid and will produce the same output. 

For someone familiar with programming concepts, these preprocessors also allow the usage of math and other functions that can be utilized for adding rules conditionally. 

Another important functionality in SASS is the use of directives. Let us explore a couple of directives called @mixin and @include. 

Syntax
@mixin name {
property: value;
property: value;
  ...
}

@mixin some-rules { 
    color: lightblue
    font-size: 25px
    font-weight: bold
}

div { 
    @include some-rules; 

There are two directives @mixin and @include, that are used here. 

In the first step, you will add properties that you want to reuse inside @mixin. 

In the second step, you use the second directive @include and add the mixin identifier that you have created using the @mixin directive. 

Similar to these, there are a couple of other directives that are also used. @import allows the import of rules from another file, and @extend allows all the rules from a specific selector to be added inside another selector. 

Stylus CSS
Now that you know how preprocessors behave let us explore one more of their type, called Stylus. If you continue to use the example above, the code for Stylus will look like this:  

body 
  font 100% Arial 
  color lightblue 

It is not hard to miss the simplicity of the code without the colons, brackets or semicolons. But you should note that it is still allowed to use all of them in Stylus without any error. Similarly, you can also use ‘$’ or any other symbol before variables, but you are not ‘required’ to do so. 

For someone unfamiliar with programming, functions are a block of self-contained code that consists of steps designed to accomplish and obtain the desired output. The preprocessors, as mentioned, allow the use of functions. Here is an example of this using Stylus.  

add(ab
  a + b 

div 
  margin add(10px, 20px

What is evident in the code above is that first, you have defined a function called ‘add’ and passed the variables ‘a’ and ‘b’ inside it. You added some functionality inside the function. In this case, you add the two values a and b with the ‘+’ or addition operator. Once you’ve done that, instead of assigning a value to the ‘margin’ property, you pass the function add with numeric pixel values passed to it. The output of this code will yield to a form ‘margin 30px’ after compilation. 

These functions are useful when adding color gradation or creating advanced geometric shapes on your web page. 

There are other features available for preprocessors too. And, just like any programming language, the space of CSS preprocessors is also competitive, and by no means are these the only options available. 

Once you have gained an understanding of regular CSS, the usage of preprocessors should be explored. The use of preprocessors today is almost inescapable given the number of advanced features they provide which are not available in conventional CSS. 

QUIZ 3 - CSS effects



Additional resources

Here is a list of resources about animation and keyframes in HTML and CSS that may be helpful as you continue your learning journey.

Transform and transition property
Detailed information about animation
Detailed information about @keyframes
More advanced examples for adding text effects (1)
More advanced examples for adding text effects (2)
More advanced examples for adding text effects (3)
Types of effects added to websites (1)
Types of effects added to websites (2)
Collection of examples using HTML/CSS

Installing a third-party Linter in VS Code

The extension you are going to use that will help you avoid errors is called Stylelint and can be found in the Extensions library of VSCode. Follow the steps below to install it and enable it to use on your CSS code. 

Step 1: Install the extension
Inside your VSCode, click on the Extensions icon and search for Stylelint. 


Click on the Install button in the Extension box that appears. 


Step 2: Ensure it is enabled
Once installed, the button will be replaced by the ‘Disable’ and ‘Uninstall’ button.

If you see ‘Enable’ instead of ‘Disable’, click on ‘Enable’ and make sure the extension is enabled. 

Step 3: Create and add a file called ‘.stylelinttrc.json’ to your project directory
The extension will look for this file inside any project folder you are working with. 

Add the rules in JSON object format as below, these are the same as the ones you used in ‘Handling errors’.

"rules": { 

        "alpha-value-notation": "number", 
        "selector-type-case": "lower", 
        "color-no-hex": true 


Additionally, you can explore their official website for other rules you may want to add.     

Step 4: Restart the VSCode
This will enable the extension completely.   

Step 5: Add .stylelint.json file inside the Extension settings
Go to the Stylelint extension again by clicking on the Extension icon and then searching for Stylelint. 

From directly next to the Stylelint title or next to the ‘Uninstall’ button, click on the ‘Settings’ icon and select ‘Extension settings’ from the drop-down list that appears.   

Note that the Extension settings will not appear unless VSCode is properly reloaded.      


After clicking on the Extension settings, scroll down until you see the section Stylelint: Config File and add the value ‘‘.stylelinttrc.json’’ under it. This is the same file name that you added inside your project folder.  


Step 6: Look at the errors 
Now you can open a CSS file and see the changes from Linter at work.

Go to View > Problems in your Menu bar. This will open the ‘Problems’ tab at the bottom.


The errors found by the Linter will display like in the screenshot above. It shows information about the rule which flagged the error. Additionally, numbers in the bracket here are respectively the line and character number for the place the error was found. 

Step 7: Light bulb


If you hover over any of the errors, a light-bulb icon will appear. If you click on it, a drop-down menu will appear. By selecting one of those options, you can explore the error that you have encountered  in further detail. 

And now you have installed and enabled Stylelint to use on your CSS code! 

Note how specific rules can be set for specific projects and the Linter extension can be enabled or disabled inside your VSCode anytime. Specific lines can also be disabled for error-checks as in the screenshot above where you can note the options for disabling the rule for the specific line or disabling a specific rule for the entire file. There are different rules that can be found as per the requirements of your project. 

There are a number of good CSS Linters that are extensions or they can be accessed from their respective websites. Some of these are mentioned in the additional readings of this section. 

Debugging the front-end

In this reading, you will learn about some of the fundamental tasks used to debug CSS. The scope of what’s covered will match the topics already covered in this course. 

You may have come across websites that have misaligned or overflowing text, broken web links or websites that take too much time to load. While the front-end and back-end both contribute to faulty web pages, visible styling is primarily concerned with the front-end. 

CSS is a styling language, unlike conventional programming languages such as Python and Java, that has controls and follows a logical structure. This can make it difficult to find the exact root of the problem. Additionally, as you know, CSS does not flag errors, and most of the ‘bugs’ that you see in CSS are aesthetic in nature and need human intervention to solve.  The task of debugging the front-end is more about experience than knowledge.   

The first step in debugging CSS is to find the root of the issue and isolate the elements involved. The majority of CSS issues will be with the layout, such as:  
  • Content overflow from parent to child or container class
  • Misplaced elements in relation to its container class   
  • Browser and device-related inconsistencies resulting in variable viewports
Isolation by reduced test case  
One way to deal with a problem is to replicate your code and systematically remove any code unrelated to the HTML and CSS elements that could be the source of the problem. The code should be distilled down to the least amount of code possible, and only then are suitable changes made to get the results you want. Alternatively, you can enable rules one at a time to observe their impact on the displayed elements.   

Items inside containers  
Often, isolation will not work, as the problem is the result of the relative mapping of elements. For example, with the misconfigured width of an item inside a flex layout. It’s important to check the use of suitable CSS properties in such cases. For a given item inside a grid, depending on the use case, width, grid-template-column, margin and padding can all be used to give spacing to an element. Additionally, you can also set different units that will all have their own behavior. In most cases, it helps to be familiar with the unit of measurement in relation to the container type to avoid misconfigurations.    

Relocating items  
Similar to the isolation of elements, you can move a certain element to observe its behavior. Doing a comparison can often help you to understand the source of the problem.   

The CSS compiler reads the elements from right to left. As an example, for a selector such as div .alpha > p, the element read first will be p before moving ‘outside’. When you change the position of the p from inside the .alpha class to some other position inside your code, it is easier to debug the source of the problem. This should be done on a case-specific basis.     

Getting familiar with the box model  
The box model is a very powerful source of information and can solve many issues with alignment. Using margin, padding and border is useful, but can be tricky and must be well understood.     

Browser issues  
Many times, the styling you have renders correctly in the IDE but misbehaves in a browser. That is because browsers have their own default CSS stylesheets called user-agent styles. While modern-day browsers are mostly compatible, you may encounter minor inconsistencies. Overriding the browser's settings can be done with universal selectors, in such cases written at the top of the code, and will include properties such as ‘margin: 0px;’ to reset the margin values set by the browser by default.     

Dev tools  
There are lots of user-friendly tools available today that can help debug CSS. However, the best tool you can use is the one provided by the browsers, called the developer tools, or dev tools. You can find these by right-clicking on a web page and selecting ‘Inspect Element’. option Note how every browser has its own expression when it comes to the configuration options, but fundamentally they are similar. Browsers today are very powerful pieces of software. If you spend time exploring the options, you may not need any other additional tools or software for debugging CSS and other front-end languages.     

A couple of the important options you can find inside your browser include:  
  • Sources: Lists the filenames such as HTML, and CSS files used by the webpage that can be explored   
  • Elements: Scrolls through the code to select a specific element for exploration    
Inside the Elements tab, on the right-hand side, you will find several options such as Computed layouts that will show the box model, Layouts that contain page and grid overlay options, and Font.    

You can select a specific element much more easily with the help of the ‘Element selection’ icon inside the dev tools. It enables the selection of specific elements on your web page. You can also access this option by hovering over a specific element on your page that will display its properties to you. 


On selecting the desired element, one way to use the Elements tab for debugging is by right-clicking on that element, scrolling to ‘Copy’ and then selecting an option from the drop-down list that appears. 


This way, you can explore the isolated code to find the problem. 

Additionally, you can add the Breakpoint option that is more useful for interactive pages by selecting the ‘Break on’ option and selecting an option from the dropdown list that appears.


Nowadays, some browsers are providing options such as Cumulative Layout Shift (CLS) that helps determine the overall efficiency of a web page. 

You can also bring up the element families by clicking on the horizontal bar: 


One very useful feature is the ability to make changes in your code directly inside the browser. First, use the ‘element selector’ mentioned above to select some elements and then look for the ‘+’ icon inside the dev tools. You can directly start adding relevant rules for that particular element which will immediately display changes on your web page. The changes you make can also be tracked from the ‘Changes’ tab. The live interactive nature of this feature greatly improves the experience of debugging. 

‘Console’ is another feature that, although it is not that useful in CSS, will come in handy as you deal with active or dynamic web pages along your developer journey.   

There are also responsive design modes in CSS that allow you to render your webpage to a specific browser or device. In addition to these, there are numerous ways in which you can explore and configure settings inside dev tools. 

When it comes to designing and styling CSS, if you don’t understand how it works, all issues will appear to be bugs. If you look at the fundamental structure of CSS, it consists of rulesets containing selectors and declaration blocks that contain properties and values. Micro-assessment of formatting and its validity can be done to troubleshoot the source of the problem. Practicing the creation of web pages and exploring the dev tools is the best way to get better at debugging and CSS in general.

In this reading, you learned about some of the fundamental tasks used to debug CSS.

QUIZ 4 - Debugging


WEEK 3 - GRADED ASSESSMENT

In this module, you will be assessed on the key skills covered in the Course.

About the portfolio project

By completing the lessons in this course, you have acquired the necessary HTML and CSS skills and knowledge to develop a home page with a header, main content and footer. You will have to decide whether you are going to use a grid or flexbox layout for your home page. Your header should contain the client logo and the main content should be a large promotional banner with three columns with text and images below it. Your footer will have two columns: the first column should have a small logo and the second one should have copywriting information. When it comes to styling, you'll have to create the appropriate look and feel for your client's target audience. Remember, you want to create intentional engagement!

To enable you to do all of this, the module covers the most essential features of your project. This includes: selecting your fictional client, working out your layout, positioning the elements, planning the user experience, creating themes and setting up your local development environment.

What is the purpose of the portfolio project?
The graded assessment will help you to establish which topics you have mastered, and which topics require further focus before you can complete the course. Ultimately, the graded assessment is designed to help you make sure that you are ready for the next course in this program. And even more, you get the opportunity to create another project for your portfolio.

How do I prepare for the graded portfolio project?
You have encountered exercises, knowledge checks, in-video questions and other assessments as you have progressed through the course. Nothing in the graded assessment will be outside what you have covered already, so you should be well placed to succeed.

What will I be doing?
The purpose of this graded assessment is to check your knowledge and understanding of the key learning objectives of this course. And what better way to do that than by applying your newly-learned skills in a practical way? You will develop a home page for one of four fictional clients. And you can read more about them in the Subject selection reading. The client you choose will determine what links, pictures and colors you will use. You are free to use your creativity but the home page needs to meet certain criteria regarding the following:
  • Visual layout
  • Semantic structure
  • CSS layout
  • CSS styling
  • CSS effects
How will I get feedback?
This is a peer-review project which means that your home page will be evaluated by your fellow learners. Of course, this means that you will also need to give feedback to your peers and grade their home pages. In this way, you can learn from other learners' ideas and the issues that they may have encountered.

The rest of this lesson will guide you on how best to approach the development of your home page.

Subject selection

For the graded assessment, you need to develop a home page for one of four fictional clients. As you read through the client personas included in this reading, think about what the ideal home page for each of these clients would look like.   

How can you use what you’ve learned over the course? For instance, how will you structure the provided information with semantic HTML tags? You can even start to think about what media elements you could include.   

And how can you create a unique user experience with CSS? Will a grid or basic flexbox serve the client best? What CSS selectors will you use to not only style your page but also create interactivity? And don’t forget about effects! It’s time to have fun and think about how you can apply what you learned about CSS animations.   

The four client personas offer a great variety for you to choose from. They are:  
  • Retail: Lucky Shrub  
  • Professional services: Hair Day  
  • Restaurant: Little Lemon  
  • Luxury jewelry: Mangata and Gallo
Read on to find out more about them.

Retail: Lucky Shrub

Based in Tuscon, Arizona, Lucky Shrub is a medium-sized garden design firm that specializes in garden design and creation, maintenance and landscaping. The company also runs a small plant nursery that sells indoor and outdoor plants, making them a one-stop shop for clients to "transform any space into an oasis you can be proud of".

Lucky Shrub was started by a husband and wife team, Jason and Maria, who share a long-time love for plants. Jason is the garden architect. He creates and oversees all designs while managing his team of landscapers. Maria manages all the marketing for the company and oversees the nursery.


Professional services: Hair Day  


Based in Madison, Wisconsin, Hair Day is a boutique hair salon that specializes in cut, color and styling. Hair Day also offers makeup and nail services, prides itself on its warm and relaxing atmosphere and is best known for edgy hair colors and on-trend cuts. The salon can only accommodate a small number of coloring appointments each week, so clients need to book far in advance. To keep clients inspired between appointments, the employees share makeup and nail tutorials on the Hair Day website. 

Pria, the owner of Hair Day, earned her certificate as a colorist and immediately started specializing in edgy, custom coloring techniques. She wanted to create a "treat yourself" environment for her clients. Pria opened the salon with her good friend and talented hairdresser, Garry. They have a staff of seven: two stylists, three colorists, one manicurist and one make-up artist.


Restaurant: Little Lemon  


Based in Chicago, Illinois, Little Lemon is a family-owned Mediterranean restaurant, focused on traditional recipes served with a modern twist. The chefs draw inspiration from Italian, Greek, and Turkish culture and have a menu of 12–15 items that they rotate seasonally. The restaurant has a rustic and relaxed atmosphere with moderate prices, making it a popular place for a meal any time of the day.

Little Lemon is owned by two Italian brothers, Mario and Adrian, who moved to the United States to pursue their shared dream of owning a restaurant. To craft the menu, Mario relies on family recipes and his experience as a chef in Italy. Adrian does all the marketing for the restaurant and led the effort to expand the menu beyond classic Italian to incorporate additional cuisines from the Mediterranean region.


Luxury Jewelry: Mangata and Gallo


Mangata and Gallo is a jewelry store that specializes in special occasions like engagements, weddings and anniversaries. The jewelry company primarily operates online and has a small storefront in Austin, Texas with an atelier attached for browsing. Mangata & Gallo's selection of jewelry is known for its high-quality and classic look. The owner, an Austin local, is well known for her jewelry designs.  

Mariana is the owner and the lead designer of Mangata and Gallo. After graduating from design school with a specialization in diamond cutting and metal smithing, Mariana opened a store in her hometown, Austin and started to grow her business online. Mariana has always managed every aspect of the business, from jewelry design to marketing to e-commerce. However, she recently hired several artisans to help craft her designs and a young employee to help manage the company website and social media accounts.


Setting up your local development environment

You have to use Visual Studio Code to complete your graded assessment. You have two options to do this. 

Option 1: Use Visual Studio Code in-browser with Coursera Labs
You can access the Visual Studio Code environment through the “ Ungraded Lab Project sandbox”  included in this lesson. Take note that the Project Sandbox only allows you to work for one hour at a time. Make sure you download your files before exiting the UGL. To work on your project again later, you can simply open the HTML and CSS files on your local machine and copy and paste the code again into the template files in the Project Sandbox. Remember to download the edited versions again at the end of the session.

To submit your project, you need to download the HTML and CSS files to your local machine and save them inside a project folder. Zip the project folder and upload it in the "My submission" area in the Peer review assessment later in this lesson.

Option 2: Work on your local device
You can also choose to complete your graded assessment on your local machine if you prefer. This will require a few steps of set up in advance. 

First, you need to download the free IDE from Microsoft's website - https://code.visualstudio.com/download.

Select the download based on your operating system.

Windows
Step 1: Download the Windows installer.

Step 2: Open the file to install it once the download is complete.

Step 3: Review and accept the license agreement, then click Next.


Step 4: Keep the default value when prompted for the destination location and click next.


Step 5: On the additional tasks view, make sure that Add to PATH is selected. 


Step 6: Click next.

Step 7: Click install when the ready to install page appears.


Step 8: Click finish once completed, and the application will launch.

Mac
Step 1: Download the application based on the chipset you have. M1 macs use Apple Silicon, and older Macs use Intel. If you are not sure, choose the Universal option.

Step 2: Go to your Downloads folder once the download is complete. 

Step 3: Double-click the zip file to extract the contents.

Step 4: Drag and drop the .app file to the application link in Finder below.


Step 5: Open the app.

Linux
Please refer to the official Linux installation guide for Visual Studio Code.

Selecting a working directory
Now that you have Visual Studio Code set up create a folder on your device that you'll use to do course exercises.

Open Visual Studio Code, go to File and select Open Folder. Using the file browser, select the folder you just created.

Creating themes

The combination of colors used in the design of a website is called the color scheme. Colors are one of the most important components of any website today because it sets the tone for the viewer. For the optimal use of colors, web developers make use of color theory and color schemes.    

Color schemes  
Fundamentally all colors are a combination of the three colors: red, yellow, and blue. These are called the primary colors. Secondary colors like orange, purple and green are a combination of two primary colors. Finally, there are six tertiary colors formed from a combination of the three primaries with secondary colors. By adding more black or more whiteyou can create lighter or darker tints of each color. All of these colors and tints make upa color wheel of 12 colors. This color wheel is the foundation for any color scheme.    

Depending on the relative positions of colors on the wheel, there are seven commonly identified color schemes according to color theory that can be used for maximum appeal. These are:     

·       Monochromatic  

·       Analogous  

·       Complementary  

·       Split complimentary  

·       Triadic   

·       Square and   

·       Rectangle  

The different combinations are represented in the image below.       



Using the color schemes  
Each of the different color schemes are used with the purpose of enhancing a website. While you can pick any of the different schemes, a practiced UX designer will considerwhether a specific type of color scheme is more suitable for certain websites than others. For example, complementary colors are well-suited for websites that will have bars and charts. It also depends on several other factors such as the number of colors that you are going to need for your webpage, the topic and domain of the webpage, user demographics of the readers and so on. For example, an informational website for medical services will typically have a white background. Other than the color schemes mentioned, even achromatic themes with only black and white color can be appealing if styling and design is well presented.

Factors to consider for themes and colors  
While color schemes serve as a guide for picking website colors, there are some factors that must be considered in the process. The user experience must be of the utmost priority as a good webpage must be able to sustain the attention of the reader withoutoverwhelming them. A good webpage will have a good balance of information and design elements. An unbalanced web design can lead to what we call as cognitive overload. Cognitive overload is when too much information or activity is presented to the user which may be detrimental to the user experience.

There is a field of research in psychology that focuses on the effects color has on the mood of a user. Nature-inspired color tones are almost universally seen to be more pleasant and add aesthetic value. As people are increasingly spending time on the internet, a good theme may make or break the appeal of a webpage. Often, it is a good idea to keep a palette of more than one color combination on hand so you can experiment with your webpage.  

A color theme on a website also plays a role in other aspects beyond the aesthetics and help in shaping the user experience of the website. A simple theme with appropriate color combinations can help a user navigate the website by creating a visual hierarchy. If for example, a user observes a specific color scheme for the subheadings, they will be able to understandwhere to look for certain information on the web page. This means you can avoid excessive design elements such as line-breaks and grids where they are not adding to the appeal of the web page.

While the experience of choosing the right colors for your website is a process of trial and error, inspiration can be drawn from a webpage that has held a personal appeal. Color theory is an important aspect of the user experience domain and plays an important role in website design so don’t be afraid to experiment with different color schemes.         

Next steps

Congratulations! You've taken another step toward improving your knowledge, skills, and qualifications. By completing this course you've acquired and practiced the core skills needed to write and test HTML and CSS code.

The next course is React Basics and in it, you'll develop a working knowledge of React. React is a powerful JavaScript library that you can use to build user interfaces for web and mobile applications (apps). In this course, you will explore the fundamental concepts that underpin the React library and learn the basic skills required to build a simple, fast, and scalable app.

Be sure to take the next course. It’s your chance to gain further insight into the world of software development. 

THANK'S FOR READING!!!

No hay comentarios:

Publicar un comentario

Foundations: Data, Data, Everywhere

Google Data Analytics Professional Certificate COURSE 1: Foundations: Data, Data, Everywhere Certified course payment here About this Course...