# CSS
###### tags: `Content`
==DEMO AS MUCH AS POSSIBLE==
## What is CSS?
CSS stands for Cascading Stylesheets. Where HTML is the structure and layout of a webpage, CSS is the styling of the webpage.
Cascading means that the styles are ordered by importance from the top down. Meaning styles at the bottom of will typically override styles above them, but we will discuss what that means coming up.
---
## Syntax
CSS is very simple and straight forward. A rule, or a block of code that defines the styling for an element, consists of selectors and name/value pairs.
CSS selectors are used to "find" (or select) the HTML elements you want to style. There are many types of selectors which we will cover shortly. But first lets take a look at the basic syntax for CSS.
```css
/* p is the selector, COLOR is the name and RED is the value */
p {
color: red;
}
```
---
## Insertion
There are three primary methods for applying styles to your webpage:
* Inline - on the HTML element itself
* Internal - in the `<head>` of every HTML document
* External stylesheet (preferred)
### Internal
It is possible to define element styles directly in the `<head>` section of an HTML document. Simply open a style tag and insert the styles inside.
```htmlmixed
<head>
<style>
p {
color: red;
}
</style>
</head>
```
### Inline
```htmlmixed
<p style="color: red;">My par</p>
```
When the web was new, these were the primary way to style elements. But imagine having to style every single element on the page or having to define styles for each page. For that reason it is recommended to use an external stylesheet.
### External Stylesheet
An external stylesheet is simply a document with the extension of `.css`. You link it in the`<head>` of every webpage you would like to use it on. It is important that it goes in the `<head>` so that your webpage elements have accessed to their styles immediately, before they are displayed.
#### Linking External Stylesheet
```htmlmixed
<link rel="stylesheet" type="text/css" href="styles.css">
```
* rel - defines the relationship to the document
* For linking stylesheets the rel will always be *stylesheet*
* href = just like an `<a>` element or link - the href is the location of your stylesheet
### Browser Styles
It is worth noting that the browser will also apply its own styles, each browser is different in this regard.
==Show user browser styles in dev tools==
### Cascading Order of Importance
Because CSS is cascading by nature, there is an order as to which styles are applied. For the three insertion types we just discussed the order is:
1. Inline styles
2. External/internal
3. Browser default
This means that internal/external styles will override browser default styling and inline styles will override both external/internal and browser default styling.
==SWITCH BACK TO HTML DOCUMENTS - OFF PLAYCODE
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a document with the extension `.css`
2. Create an HTML document
3. Link your new stylesheet in the `<head>` of your new HTML document (use relative path)
4. Add a paragaph to the HTML document
5. Style the paragraph to make it blue
6. Save both documents and open in your browser
==KNOWLEDGE CHECK==
1. What is CSS?
2. What are the three ways to insert styles into your HTML document?
3. What is the preferred method for inserting styling?
==QUESTIONS?==
---
## Comments
Every language has comments and they always exist for the same reasons. CSS is no different in that regard.
### Syntax
```css
/* This is a single line comment */
/* This is
a multi-line
comment */
/*
p {
color: red;
}
*/
```
### A Note on Comments
Comments are very useful but be careful, it is entirely possible to comment a block of code out on accident which would prevent it from executing.
> Remember: The comment does not end until the closing comment tag, this is true for any language.
```css
/*
Anything below this line will not execute
Because it is missing an end tag
p {
color: red;
}
```
---
## Selectors
As we covered earlier, selectors are essentially the element or elements you would like to define styles for. There are quite a lot of ways to create selectors but we will cover the most commonly used.
> Remember: Everything that is covered in this course and regarding development in general can be researched and bookmarked. Every language has its own documentation and if you can't find the answer, chances are Google has you covered.
### Element Selector
The element selector is exactly what it sounds like, you use the element type itself as the selector to define styles.
Simply use the element name in your stylesheet:
```css
p {
color: red;
}
/* You can also combine multiple */
p, h1 {
color: red;
}
```
### Universal
The universal selector is used to target all elements on the page. Therefore, it is not recommended to use this selector unless it really makes sense.
Use the universal selector in your stylesheet. The symbol for this selector is an asterisk:
```css
* {
color: purple;
}
```
### IDs
An ID is a powerful selector for styling HTML elements. It is called an ID as in identifier because it is unique and should always be unique. Meaning there should only ever be one ID with a given name per stylesheet.
First you apply the ID to your element as a name/value pair:
```htmlmixed
<p id="my-id">This is an element with an ID</p>
```
Next you reference that ID in your stylesheet. The selector for an ID is `#` (pound symbol):
```css
#my-id {
color: red;
}
```
> TIP: Do NOT include spaces between the pound symbol and the ID name
> Best Practice: For CSS if you need to use more than word, separate the words with a dash
### Classes
Classes are equally as powerful in CSS! A class is called a class because it is a grouping of elements. This means that you can style multiple elements by simply applying a class with the same name to each of them.
First you apply the class to your elements as a name/value pairs:
```htmlmixed
<p class="par">Par 1</p>
<p class="par">Par 2</p>
```
Next you reference that class in your stylesheet. The selector for an class is `.` (period):
```css
.par {
color: red;
}
```
You can also add multiple classes to the same element.
```htmlmixed
<p class="par one">Par 1</p>
<p class="par two">Par 2</p>
```
Now the styling of `color:red` will be applied to both paragraphs, or rather any element with the class of *par*.
> Note: It is perfectly valid to use only classes and never use IDs. It is possible that you might apply an ID to an element only to need to apply a class later. For that reason some developers only use classes to avoid removing the ID and applying a class at a later time.
### Combinators
You can also combine selectors to ensure you target exactly the element or elements that you want to style.
#### Multiple Classes
As I mentioned above you can add multiple classes to the same element. Say you wanted two paragraphs to be blue but you wanted just one to be italic.
You would just use the classes together, with NO space.
```css
.par {
color: blue;
}
.par.one {
font-style: italic;
}
```
#### Descendent Selector
The descendant selector matches all elements that are descendants of a specified element.
```htmlmixed
<div>
<p>one</p>
<p>two</p>
</div>
<p>outside</p>
```
```css
/* Will select all paragraphs that are inside a div */
div p {
color: green;
}
p {
color: blue;
}
```
#### Child Selector
The child selector selects all elements that are the children of a specified element.
Symbol: `>`
```htmlmixed
<div class="my-class">
<p>one</p>
<p>two</p>
</div>
<p>outside</p>
```
```css
/* If you elements with the class of 'my-class', this combinator will ONLY select the paragraphs inside that element */
.my-class > p {
color: green;
}
p {
color: blue;
}
```
#### Adjacent Sibling Selector
The adjacent sibling selector selects all elements that are the adjacent siblings of a specified element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".
Symbol: `+`
```htmlmixed
<div>
<p>Paragraph 1 in the div.</p>
<p>Paragraph 2 in the div.</p>
</div>
<p>Paragraph 3. I am immediately following the div element</p>
<p>Paragraph 4. Not in a div.</p>
```
```css
div + p {
color: green;
}
```
#### General Sibling Selector
Similar to the adjacent sibling selector except it selects ALL siblings of a specific element.
Symbol: `~`
```htmlmixed
<p>Paragraph 1.</p>
<div>
<p>Paragraph 2.</p>
</div>
<p>Sibling</p>
<h1>I am a sibling as well but I am not a paragraph</h1>
<p>I am a sibling of the div</p>
```
```css
div ~ p {
color: green;
}
```
> Note: It is not required to use a specific selector whether it is an ID, class or something else. It is completely up to you how you target your elements to style them.
> Note: The goal is not to memorize all of the possible selectors because there are just too many. There are plenty of cheatsheets and references out there, use them when you need them. After you have been developing for awhile you will begin to memorize the important ones and know when to use which selectors. Don't focus too much on that right now.
==EXERCISE==
> Place in chat
> Have them share their screen
> Remind them that the more we repeat this process the easier it will be for them going forward
1. Create a document with the extension `.css`
2. Create an HTML document
3. Link your new stylesheet in the `<head>` of your new HTML document (use relative path)
4. Add 3 paragaphs to the HTML document
5. Apply the class of "my-class" to 2 paragraphs
6. Style the "my-class" classes to be color: green;
7. Apply an ID of "my-id" to the third paragraph
8. Style the "my-id" ID to be colored red
9. Add a CSS rule with the selector of "*" and a color of purple
10. Save both documents and open in your browser
==KNOWLEDGE CHECK==
1. What is a class?
2. What is an ID?
3. When do you think it would make sense to use a class instead of an ID?
==Bookmark This==
https://www.w3schools.com/cssref/css_selectors.asp
==QUESTIONS?==
---
## Box Model
The box model often gets confusing if not explained simply, so I will endeavor to explain it as simple as possible. Every element on an HTML page is a box of some sort. Each square or element has the potential to have padding, a border and margin. The box model simply describes the order of the items.
We will discuss what padding, margin and borders are coming up but I wanted to make sure you had a chance to view the box model before we started using it.
This is what it looks like:
https://www.kasandbox.org/programming-images/misc/boxmodel.png
==Show user in dev tools - use the box model visualizer==
---
## Measurement Units
Before we go to much longer I want to make sure we discuss measurement units. Many CSS rules such as height or width or padding - require measurement units. There are two types of units - relative and absolute.
### Absolute
* cm - centimeters
* mm - millimeters
* in - inches
* px - pixels
* pt - point
* pc - picas
> Best Practice: If you are going to use an absolute measurement, pixels are typically the go to.
Usage:
```css
/* No space between value and measurement unit */
p {
width: 50px;
}
```
### Relative Units
Relative units are more commonly used these days because they have the ability to scale up and down with the size of your screen. Pixels, for example, are absolute so they will always be the same size.
So if you set the font size to 50px it will be 50px on big screen and small screens alike, which may cause usability issues. Relative units, on the otherhand will get bigger or smaller based on the size of the the screen.
* em - Relative to the font-size of the element
* rem - relative to the font-size of the root element
* vw - relative to the view width
* vh - relative to view height
* % - relative to parent element
> Note: Deciding which measurement unit to use is purely preferential. Typically relative units are used for responsive development (mobile design) but some developers prefer use pixels. Some companies have set design patterns and will let you know what they prefer. Otherwise, feel free to experiement with these units.
> Note: Units can be used for anything that requires a measurement unit including height, width, font-size and much more.
==Show user different units in PlayCode==
---
## Padding
Padding is the first item in the box model outside of the content itself. It is used to provide spacing between the content and other elements. If the element has a border the padding will provide spacing between the content and the border.
Padding requires a measure
> 4 possible values (clockwise) because all elements have four sides
```css
p {
padding: top right bottom left;
/* Will apply 5px to both the top and bottom and 100px to both the left and the right */
padding: 5px 100px 5px 100px;
/* Same thing - shorthand */
padding: 5px 100px;
/* Will apply 5px of padding to all four sides */
padding: 5px 5px 5px 5px;
/* Same things - shorthand*/
padding: 50px;
/* Will apply 5px to the top, 20px to the right, 30px to the bottom and 40px to the bottom */
padding: 5px 20px 30px 40px;
/* If you omit the 4th value it will apply the padding of the right side value to the left side.
* This is because of the pattern {top right bottom left}, it has the top and bottom values but it doesn't have BOTH of the left and right values, so it makes an assumption.
Avoid this where possible
* */
padding: 5px 10px 4px;
}
```
> Note: You can use however many values you wish whether it is 1 or all 4
> Note: The clockwise pattern applies to any style that can be applied to all four sides of the element
>
---
## Border
```css
p {
border-left
border-right
border-top
border-bottom
/* Shorthand */
border: measurementUnit borderStyle color;
/* Width */
border-width: 20px;
}
```
Border Styles:
* dotted
* dashed
* solid
* double
* groove
* ridge
* inset
* outset
* none
* hidden
> Remember: Borders can be applied to any of the 4 sides of an element or none at all
> Note: The shorthand syntax can be used for any style that can have 4 values
---
## Margin
Since margin is the last element in the box model, it is a great way to provide spacing around your element or between your element and another element.
```css
p {
margin-left
margin-right
margin-top
margin-bottom
/* Shorthand */
margin: measurementUnit;
}
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a document with the extension `.css`
2. Create an HTML document
3. Link your new stylesheet in the `<head>` of your new HTML document (use relative path)
4. Add 2 paragaphs to the HTML document
5. Apply a unique ID to all 3 paragraphs
6. Apply 5vw of padding to paragraph 1
7. Apply a left and right border of `5px solid red` to the second paragraph
8. Save both documents and open in your browser
==KNOWLEDGE CHECK==
1. What is the box model?
2. What is padding?
3. What is margin?
4. What is the difference between margin and padding?
5. What order does CSS use when providing 4 values?
==QUESTIONS?==
---
## Height/Width
As you would imagine when styling a webpage there are quite of lot of times that you would need to set the height or width of an element.
Values:
* auto - This is default. The browser calculates the height and width
* length - Defines the height/width in px, cm etc.
* % - Defines the height/width in percent of the containing block (relative to parent)
* initial - Sets the height/width to its default value
* inherit - The height/width will be inherited from its parent value
If your element has content such as a paragraph with some text, the browser will give it height and width so it will be visible. However, if you have an empty div for example, if you don't set the height and width explicitly you will not see it.
> Note: If the browser applies `display: block;` to the element it will have width by default
>
==Show inherit in PlayCode==
---
## Text Formatting
It is very common to need to format or style text.
### Alignment
Just like microsoft word you can set the text alignment to left, right, center or alignment.
```htmlmixed
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Repudiandae numquam magni fugiat sint cumque. Unde ad accusantium fugit tempora quibusdam. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolore est incidunt facilis tenetur impedit pariatur fugit aspernatur velit repellendus iure.</p>
```
Values:
* left
* center
* right
* justify
```css
p {
background: grey;
text-align: left;
padding: 20px;
width: 50%;
}
```
### Text Decoration
Values:
* underline
* overline
* line-through
* none
### Text Transformation
Values:
* uppercase
* lowercase
* capitalize
### Text Spacing
* text-indent
* letter-spacing
* line-height
> Note: line-height is used often
---
## Fonts
There are many font properties you can apply to some text to make it look the way you want.
### Font Family
Font families will be executed in the order they are provided. Make sure to provide a fallback font if possible.
Put specific font-family names in quotes.
```css
p {
font-family: desiredFontFamily, fallback, genericType (serif);
/* If it cannot find your desired font-family it will use the fallback */
/* If it cannot find the fallback it will use the generic type if provided*/
font-family: "....", sans-serif;
}
```
### Font Style
Values:
* normal (default)
* italic
* oblique (rarely used)
### Font Size
Sets the size of the text. You can use absolute measurement units or relative.
```htmlmixed
<p class="one">Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat, nemo.</p>
<p class="two">Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum, animi.</p>
```
```css
p {
&.one {
font-size: 16px;
}
&.two {
/* Relative to the width of the viewport */
font-size: 2vw;
}
}
```
> Note: Relative units do not have minimums so it is possible for them to be too small to be readable
>
### Font Weight
Keyword values
* font-weight: normal;
* font-weight: bold;
Keyword values relative to the parent
* font-weight: lighter;
* font-weight: bolder;
Numeric keyword values (some only available if the font-family has them)
* font-weight: 100;
* font-weight: 200;
* font-weight: 300;
* font-weight: 400; // normal
* font-weight: 500;
* font-weight: 600;
* font-weight: 700; // bold
* font-weight: 800;
* font-weight: 900;
Global values
* font-weight: inherit;
* font-weight: initial;
* font-weight: unset;
==Questions?==
---
==Starting using HTML doc instead of PlayCode==
## CDN
Before we go too much further it is important to explain the usage and importance of a CDN or Content Delivery Network. Typically if you have a server in California and are trying to access it in Hong Kong, for example, the network request has to make several hops to get its payload and return. This can be pretty slow depending on the distance from the server hosting the files and the computer requesting the files.
A Content Delivery Network is a group of servers that are distributed geographically so that the distance between the server hosting the files and the computer requesting the files is never very far. That means faster requests.
While you can download plugins and fonts and any other things during the course of development, it is typically preferred to use a CDN if available. Using a CDN also ensures that the files you are using stay up to date because you don't have to download the files each time a new update comes out. The CDN is updated so then the files you are using are updated as well.
==Questions?==
---
## Web Fonts
Web fonts allow you to use fonts that are not installed on your computer.
Formats:
* TrueType (TTF) - most common format for Mac and Windows
* OpenType (OTF) - a Microsoft font format for scalable computer fonts
* Web Open Font (WOFF) - OpenType or TrueType but supports better compression and additional metadata
* SVG - scalable vector
* Embedded OpenType (EOT) - a compact form of
> Remember: Like many things in development, you do not need to memorize these font formats or even really worry about their differences right now. The most important thing that we will discuss in this submodule is the actual implementation of web fonts.
### Insertion
Much like the CSS file itself there are multiple ways to reference web fonts so that your webpage has access to them.
#### In the `<head>`
Most font libraries have their fonts hosted so you can include the link in the `<head>` of each page you would like to have access to the font. Then it is as simple as referencing the font name when you use the `font-family` rule that we discussed previously.
Lets use Google fonts, a popular web font library as an example.
==Open Google fonts and show use how to select font==
https://fonts.google.com/
```htmlmixed
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
</head>
```
```css
p {
font-family: 'Roboto', sans-serif;
}
```
> Note: The link we used to reference the font in the HEAD is an example of CDN usage.
> Remember: Remember when I said that only certain font families have certain font-weights available? Well if you click *customize* when selecting your Google font you can define which font weights you want the font-family to have.
#### Downloaded
If you would like to host the font locally you can do that as well. Best practice is to create a *fonts* folder to store any custom fonts or web fonts that you use.
```css
@font-face {
font-family: myFirstFont;
src: url(pathToFontFile);
}
/* Usage */
p {
font-family: myFirstFont;
}
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a CSS document
2. Create an HTML document
3. Link your new stylesheet in the HEAD of your new HTML document (use relative path)
4. Add 2 paragaphs to the HTML document
5. Apply a unique ID to each paragraph
6. Go to Google Fonts (https://fonts.google.com/) and choose a font
7. Reference font in the HEAD
8. Apply that font to 1 of your 2 paragraphs
9. Create a directory named "Fonts"
10. Go back to Google fonts and choose a DIFFERENT font
11. Download the font to your Fonts folder
12. Apply that font to the second paragraph
13. Save both documents and open in your browser
==QUESTIONS?==
---
## Icons
Every webpage uses an icon in some form. Icons are very similar to web fonts. You can reference them in the HEAD of your HTML pages or download them directly. The main difference is that you usually don't need to use CSS to utilize them, however it does depend on the library.
One of the most popular (free) icon sets/libraries is Ionicons. Lets go there:
https://ionicons.com/v1/
The first thing we want to do is see if the library hosts there icons via CDN. They do so lets add that to the HEAD of our HTML doc.
```htmlmixed
<head>
<link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
</head>
```
To use the icon we need to use an `<i>` HTML element and give it a class. The class is what the library uses to determine which icon to serve. This varies
```htmlmixed
<i class="ion-pie-graph"></i>
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create an HTML document
2. Open Ionicons (https://ionicons.com/)
3. Reference the CDN link in the HEAD
8. Add an icon to the page
9. Save the HTML page and open it in your browser
==QUESTIONS?==
---
## Links
Links have their own states and the color of the link will change depending on what state the link is in.
States
* a:link - univistied (default state)
* a:visited - visited link
* a:hover - when hovered
* a:active - the moment a link is clicked
Links have an underline by default. You can remove this underline by using the `text-decoration:none` style.
==QUESTIONS?==
---
## Lists
There are a lot of ways to style lists but the main way to style a list is to define a list style type.
```css
li {
list-style-type: circle | square | upper-roman | lower-alpha;
}
```
---
## Tables
If you remember from the HTML module, tables are made up of 4 primary elements:
* table - main wrapper
* th - table header
* tr - table row
* td - table data or cell
You can apply styling to any of those elements. Whether that is a border or color or something else. However, there are a couple of tips and tricks that I want to bring to your attention.
### Layout
By default, tables columns will take up the amount of width that they need. While that is convenient, it doesn't give the table the cleanest look. The `table-layout: fixed` style will set all the columns to the same width. The table itself will need to have an explicit width set for this to take effect. Let me show you what I mean:
==Demo in PlayCode==
```htmlmixed
<table>
<tr>
<th>Header 1</th>
<th>This is a longer header</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data/Cell 1</td>
<td>Data/Cell 2</td>
<td>Data/Cell 3</td>
</tr>
</table>
```
```css
table {
/* Add fixed layout */
width: 50%;
* {
border: 1px solid grey;
}
}
```
### Striped Rows
You can also easily add a background to every other row in the table. We did not cover the `:nth-child` selector but it basically selects every element that is the second child of its parent. I will show you how to use it.
```css
/* For nth-child you can pass in a number or odd/even */
/* For a table we may not know how many rows there are so using odd or even works great */
/* This means that every odd row it will apply a grey background */
tr:nth-child(odd) {
background: grey;
}
```
As with everything, there are a lot of ways to style a table but those are just a couple of the tips that should help create better looking tables.
==Questions?==
---
## Display
Display is one of the most important and widely-used properties in CSS. It determines if and how an element is displayed in the browser.
### Block Level Elements
A block level element always starts on a new line and takes up the full width available unless the width is otherwise specified. There are many elements that are block-level by default:
```css
div {
display: block;
}
```
* div
* h1 - h6
* p
* form
* header
* footer
* section
### Inline Elements
An inline element does not start on a new line and only takes the amount of width necessary.
Inline element examples:
* span
* a
* img
```css
div {
display: inline | inline-block;
}
```
#### `display: inline` vs. `display: inline-block`
* `inline-block` will allow you to set a height/width on an element, `inline` will not
* with `inline-block` the top and bottom margins/paddings are respected, with `inline` they are not
* elements can sit next to eachother
```htmlmixed
<p class="inline-example">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusamus est, voluptates natus dolorum eveniet ut illo? Repudiandae accusantium perspiciatis qui?</p>
<p class="inline-example">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Commodi, excepturi iure? Quia illo, iste aliquam laborum doloribus tempora? Id, delectus.</p>
<br/>
<p class="inline-block-example">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Accusamus est, voluptates natus dolorum eveniet ut illo? Repudiandae accusantium perspiciatis qui?</p>
<p class="inline-block-example">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Commodi, excepturi iure? Quia illo, iste aliquam laborum doloribus tempora? Id, delectus.</p>
```
```css
.inline-example {
border: 1px solid red;
width: 100px;
/* Will set next to each other but as you can see the width does not work */
display: inline;
}
.inline-block-example {
border: 1px solid blue;
width: 100px;
display: inline-block;
}
```
### Hiding an Element
```css
p {
/* This means that the element will not take any height or width in the document flow */
display: none;
}
```
### Visibility
The visibility property is much like the display property with one major difference: it will still affect the layout.
```htmlmixed
<div class="container">
<div class="inner"></div>
<div class="inner hidden"></div>
<div class="inner"></div>
</div>
```
```css
.container {
background: red;
width: 100%;
height: 400px;
}
.inner {
width: 100px;
height: 100px;
margin-bottom: 10px;
background: blue;
}
.inner.hidden {
visibility: hidden;
/* vs */
/* display: none; */
}
```
==Allow use to switch back to PlayCode==
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Create a form (POST method, no action) with 3 inputs with EITHER placeholders or labels (first name, last name, email)
3. Put first name and last name inputs on the same line
4. Add an input with the class of "hidden"
5. Hide the "hidden" input
6. Name/save project
==KNOWLEDGE CHECK==
1. What is a block level element?
2. What is an inline element?
3. What is the difference between `display: none` and `visibility: hidden`?
==QUESTIONS?==
---
## Position
The position property is one of the hardest properties to understand so we will spend as much time here as it takes for you to be confident using it.
Values:
* static - default/normal position
* relative - allows the element to be moved away from its original position, relative to its parent
* fixed - relative to the viewport so it does not move, even when scrolled
* absolute - relative to the nearest positioned element
* sticky - based on the users scroll position (rarely used)
All of have top, right, bottom and left values available that can be set to move or position an element. Negative values can be used.
### Relative
```htmlmixed
<div class="grey">
<div class="red">
<div class="blue"></div>
</div>
</div>
```
```css
.grey {
width: 500px;
height: 200px;
background: grey;
}
.red {
width: 100px;
height: 100px;
background: red;
}
.blue {
width: 50px;
height: 50px;
background: blue;
position: relative;
top: 25px;
left: 25px;
}
```
Notice how the blue square is positioned relative to its parent, the red square. We set it to be moved 25px down from the top and 25px over from the left, inside the red square.
### Absolute
```htmlmixed
<div class="grey">
<div class="red">
<div class="blue"></div>
</div>
</div>
```
```css
.grey {
width: 500px;
height: 200px;
background: grey;
position: relative;
}
.red {
width: 100px;
height: 100px;
background: red;
}
.blue {
width: 50px;
height: 50px;
background: blue;
position: absolute;
top: 0;
right: 0;
}
```
Notice how we set the blue square to be all the way to the top and all the way to the right. It is outside of the red square because the red square is not relatively positioned. Absolutely positioned elements look for a parent with relative positioning and base their coordinates on that parent. The outermost div - the grey element has relative positioning, that is why the blue square is at the top right of that element.
### Fixed
Fixed is often used for navigation bars so that the nav bar stays on the top of the screen while the user scrolls.
```htmlmixed
<nav></nav>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
```
```css
nav {
background: #ccc;
width: 100%;
height: 45px;
position: fixed;
}
.section {
width: 100%;
height: 800px;
background: cornflowerblue;
border: 2px solid white;
}
```
### Element Ordering with `z-index`
If, and only if, an element has a position property set - z-index can be used to specify the stack order of elements. Every now and then depending on positioning, elements will overlap. The z-index will allow you to control the stack order of the elements.
```htmlmixed
<div class="grey">
<div class="red"></div>
<div class="blue"></div>
</div>
```
```css
.grey {
width: 500px;
height: 200px;
background: grey;
}
.red {
width: 100px;
height: 100px;
border: 2px solid red;
position: relative;
z-index: 2;
}
.blue {
width: 50px;
height: 50px;
background: blue;
position: absolute;
top: 70px;
z-index: 1;
}
```
Now in this example the blue square is NOT inside of the red square, it is outside. I used absolute positioning to place it over red square. Notice how the blue square is BEHIND the border of the red square. That is because I set the z-index of the blue square to 1 and the z-index of the red square to 2. It is just about ordering.
> Remember: The z-index property will not work if the element does not have a position value set.
>
### Use Case
I think the best thing to do right now would be to provide a use case scenario so you can see one reason for why positioning could be valuable. Placing text over an image is 100% something you will be asked to do at some point.
Take this HTML for example. Because paragraph elements are block level, they will take take up the full width by default. But if we make the paragraph absolutely positioned and make the container relatively positioned, the text will be on top of the image.
```htmlmixed
<div class="container">
<img src="https://images.pexels.com/photos/814499/pexels-photo-814499.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="">
<p>Inspirational quote here</p>
</div>
```
```css
.container {
position: relative;
}
p {
position: absolute;
top: 0;
left: 0;
color: red;
font-size: 40px;
}
```
So just to summarize: Absolutely positioned elements base their positioning off of the nearest parent with relative positioning. In this case the ".container" is that parent so the paragraph is removed from the normal document flow and laid on top of the image.
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add an image
3. Put the text "I'm over an image!"
4. Name/save project
==KNOWLEDGE CHECK==
1. What is absolute positioning?
2. What is relative positioning?
3. If you were going to make a nav bar that stayed at the top of the screen, what positioning would you use?
==QUESTIONS?==
---
## Overflow
The overflow property allows you to determine if you want to add a scrollbar or clip the content if it is too big for its parent container.
Values
* visible - not clipped, default
* hidden - clipped, anything outside of the width/height of the container is cropped/not visible
* scroll - will add scrollbars to access the content that has overflowed outside the original constraints of the container
* auto - same as scroll but only adds scrollbars when necessary
```htmlmixed
<div class="container">
<div class="content"></div>
</div>
```
```css
.container {
height: 100px;
width: 100px;
border: 3px solid red;
}
.content {
height: 200px;
width: 200px;
background: green;
}
```
As you can see the text is flowing outside of the container, in most situations this is not optimal. We want to control the overflow of the text inside of our container.
```css
.container {
height: 100px;
width: 100px;
border: 1px solid red;
/* Clips the overflowed content */
overflow: hidden;
/* Adds vertical scroll bar */
overflow: scroll;
/* Uses save values as overflow but ONLY for horizontal overflow */
overflow-x: values;
/* Uses save values as overflow but ONLY for vertical overflow */
overflow-y: values;
}
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Make 2 scrollable columns of text beside each other (columns)
==KNOWLEDGE CHECK==
1. How would you style an element if want it to be scrollable horizontally but not vertically?
==QUESTIONS?==
---
## Float
Floating is a method for positioning elements to the left or right. Due to all of the methods we have for positioning elements these days floats are rarely used. However, floating used to be a great way to position elements next to each other.
Values:
* left
* right
* none - default
* inherit (inherits from parent)
```htmlmixed
<div class="container">
<p class="left">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ut, neque!</p>
<p class="right">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Laboriosam, veritatis.</p>
</div>
```
```css
.left {
border: 1px solid blue;
float: left;
}
.right {
float: right;
border: 1px solid red;
}
```
As you may remember from the display submodule we recently covered - paragraph elements are block level elements by default. That means they will sit on their own line. But as you can see using the float property has allowed the elements to sit next to each other.
### Clearing Floats
If an element is floated, the element that comes after it in the document flow will do its best to be on the same line as the floated element. Most of the time you don't want the element to do that. If you are creating two columns for example, you just want two columns on one line and nothing else. Clearing will make sure the element sits on its own line.
> Note: Having to clear floats is yet another reason why floats are not used anymore.
Values:
* left - clear elements that are floated left
* right - clear elements that are floated right
* both - clear all floats
```htmlmixed
<div class="container">
<p class="left">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ut, neque!</p>
<p class="right">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Laboriosam, veritatis.</p>
<p class="cleared">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ea, corporis! Rem quidem illo quisquam. Necessitatibus quidem veniam ullam exercitationem unde.</p>
</div>
```
```css
.left {
border: 1px solid blue;
float: left;
}
.right {
float: right;
border: 1px solid red;
}
.cleared {
clear: both;
}
```
### Float vs. `inline-block`
You might be wondering what the difference between using float and `inline-block` is, since they both allow you to put elements beside each other. The basic difference is that content will flow around a floated element.
```htmlmixed
<img src="https://img.etimg.com/thumb/msid-68721417,width-643,imgsize-1016106,resizemode-4/nature1_gettyimages.jpg" alt="">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus, cupiditate. Placeat aspernatur est, at aut magnam facere? Earum minima, eligendi impedit nisi maxime nemo delectus quas distinctio cumque explicabo consectetur animi cupiditate debitis quis esse non beatae? Odit molestias pariatur odio, quisquam quia laborum aliquid unde ratione quae, deleniti ex, repudiandae commodi cupiditate quis eveniet fugit. Hic fuga laborum sit libero voluptates sapiente reprehenderit quisquam odit harum? Consequatur quisquam assumenda nam nihil voluptatum beatae enim laudantium aliquam reprehenderit suscipit impedit distinctio iste, possimus, cupiditate eveniet ex dolore iusto dicta soluta, id odio ipsa aliquid? Nulla sequi dignissimos numquam consectetur earum culpa in nihil rerum vitae porro, eaque architecto! Et inventore numquam ipsum magni nobis dicta dolor sint excepturi impedit vel eius eum, ipsam incidunt quisquam, aliquam repellendus neque quidem deserunt vero? Eius vero quo iste libero hic, porro ipsam nam maxime adipisci voluptatem? </p>
```
```css
img {
float: left;
height: 100px;
width: 140px;
}
```
> Note: This is a big reason floats are not used anymore.
### Clearfix
Another reason floating is not used often is because floated content can overflow outside of its parent container/element.
```htmlmixed
<div class="container">
<img src="https://img.etimg.com/thumb/msid-68721417,width-643,imgsize-1016106,resizemode-4/nature1_gettyimages.jpg" alt="">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus, cupiditate. Placeat aspernatur est, at aut magnam facere? Earum minima, eligendi impedit nisi maxime nemo delectus quas distinctio cumque explicabo consectetur animi cupiditate debitis quis esse non beatae? Odit molestias pariatur odio, quisquam quia laborum aliquid unde ratione quae, deleniti ex, repudiandae commodi cupiditate q </p>
</div>
```
```css
.container {
width: 100%;
border: 2px solid blue;
}
img {
float: left;
height: 100px;
width: 100px;
}
```
Here we can see that the image is flowing outside of its parent container. If there was an element under the container it would likely run into the image. The only way to solve this is to apply a clearfix, or simply put, a method for keeping floated elements inside of their parent.
> Note: We have NOT covered pseudo selectors yet so don't worry too much about the syntax I will be using.
```css
.container:after {
content: "";
clear: both;
display: table;
}
```
> Note: We are not going to do an exercise here because floats really shouldn't be used.
==KNOWLEDGE CHECK==
1. What is the purpose of using floats?
2. Why is floating a bad idea?
==QUESTIONS==
## Transforms
Since we have been talking about positioning we will soon be talking about centering elements both vertically and horizontally. But before we do that, it will be helpful to cover transforms.
Transforms allow you to transform elements in simple ways such as scaling to more advanced things like changing the shape of an element.
All transforms can be applied to the x-axis, y-axis or both. The values you provide are placed inside of parenthesis and are called paramters. Negative parameter values are valid.
### Translate
Translate is very similar to absolute positioning in that it allows you to move an element. However, instead of using coordinates such as `top` or `left`, you move the element a specific distance from its original position. You can move the element horizontally using the x-axis or vertically using the y-axis.
```htmlmixed
<p class="column one">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ut, accusamus.</p>
<p class="column two">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Ut, accusamus.</p>
```
```css
.column {
width: 120px;
display: inline-block;
border: 1px solid red;
}
.one {
/* As you can see translate does not care if it causes an overlap onto another element */
/* That said, be mindful when choosing how to position your elements, translate isn't always the right solution */
transform: translateX(50px);
/* Shorthand */
/* If you do not specify translateX or translateY, you must provide x/y values WITH a comma */
/* If you omit the y value, it will be set 0 */
transform: translate(x, y);
}
```
> Remember: No matter what you are providing measurement values for, you can use whatever unit you prefer, we are only working with pixels because they are predictable.
### Rotate
Rotate allows you to rotate an element a specific amount of degrees.
```htmlmixed
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Repudiandae, nobis?</p>
```
```css
p {
margin: 10px;
border: 1px solid blue;
width: 100px;
/* The shorthand only requires one value, using two values is invalid */
transform: rotate(-90deg);
/* If you would like to rotate a specific axis you need to specify that axis like this */
/* Be careful when you rotate a specific axis, it may look like it is shrinking the element but it is in fact rotating it */
transform: rotateX(80deg);
}
```
### Scale
Scale allows you to increase or decrease the width and height of an element. The parameters that
```htmlmixed
<div class="container">
<img src="https://img.etimg.com/thumb/msid-68721417,width-643,imgsize-1016106,resizemode-4/nature1_gettyimages.jpg" alt="">
</div>
```
```css
.container {
width: 300px;
height: 300px;
border: 2px solid red;
}
img {
width: 300px;
height: 300px;
}
```
As you can see we have not applied a transform yet, and the image fits within the bound of the parent container.
```css
img {
width: 300px;
height: 300px;
/* Here we have scaled the image 1.5x the height AND width */
transform: scale(1.5);
}
```
Now, as you can see the image has flowed outside of the bound of its parent, so again be mindful of this when using transforms.
We can also choose to scale JUST the width or JUST the height.
```css
img {
width: 300px;
height: 300px;
transform: scaleX(1.5);
transform: scaleY(1.5);
}
```
### Skew
The skew transform will be easier to show you than to explain. It does, however, have the same syntax as rotate, it takes degrees.
```htmlmixed
<div class="block"></div>
```
```css
.block {
height: 100px;
width: 100px;
background: #ccc;
transform: skew(-20deg);
}
```
As you could imagine, the skew transform isn't used often.
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add an image and set the height/width to 200px
3. Transform the image by scaling it to twice its height/width
==QUESTIONS?==
---
## Centering
We have talked a lot about positioning elements, but have yet to cover how to center elements, horizontally and vertically.
### Horizontal Centering
It is actually pretty easy to horizontally center an element.
#### Method 1: `margin: 0 auto`
```htmlmixed
<div class="container">
<div class="block"></div>
</div>
```
```css
.container {
background: grey;
height: 500px;
width: 500px;
}
.block {
background: blue;
height: 100px;
width: 100px;
/* This is the important part! */
margin: 0 auto;
}
```
#### Method 2: Transforms
```htmlmixed
<div class="container">
<div class="block"></div>
</div>
```
```css
.container {
background: grey;
height: 500px;
width: 500px;
/* Needs to be relative for absolutely positioned block */
position: relative;
}
.block {
background: blue;
height: 100px;
width: 100px;
/* The important parts */
position: absolute;
left: 50%;
transform: translateX(-50%);
}
```
> Note: When you set the left and right values for margin to auto, the browser calculates how much margin to use based on the width of your element and applies that amount to each side.
> Note: The `margin: 0 auto;` trick only works with block level elements. So inline elements like images will need to have `display: block` set on them for this to work.
> Note: If you are attempting to center text, `text-align:center` is your best bet.
### Vertical Centering
Vertical centering used to be much more difficult, but thanks to transforms it is much easier now.
```htmlmixed
<div class="container">
<div class="block"></div>
</div>
```
```css
.container {
background: grey;
height: 500px;
width: 500px;
/* Needs to be relative for absolutely positioned block */
position: relative;
}
.block {
background: blue;
height: 100px;
width: 100px;
/* The important parts */
position: absolute;
top: 50%;
transform: translateY(-50%);
}
```
### Dead Center (Horizontal/Vertical)
```htmlmixed
<div class="container">
<div class="block"></div>
</div>
```
```css
.container {
background: grey;
height: 500px;
width: 500px;
/* Needs to be relative for absolutely positioned block */
position: relative;
}
.block {
background: blue;
height: 100px;
width: 100px;
/* The important parts */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add an image
3. Place a paragraph over the image
4. Center the paragraph both horizontally and vertically
5. Name/save project
==QUESTIONS?==
---
## Pseudo Class
A pseudo-class is used to define a special state of an element.
### Syntax
```css
selector:pseudo-class {
property:value;
}
```
### Hover
Hover is probably the most-used pseudo-class. It allows you to enforce a hover state when placing your cursor over an element.
```htmlmixed
<div class="block"></div>
```
```css
.block {
background: red;
width: 50px;
height: 50px;
}
.block:hover {
background: blue;
}
```
### The `:first-child` Pseudo-class
Sometimes you want to only select the first child of an element, in fact this occurs more often than you probably think! The good news is there is a pseudo-class for that!
```htmlmixed
<div class="block">
<p>Par one</p>
<p>Par two</p>
<p>Par three</p>
</div>
```
```css
.block {
background: grey;
width: 200px;
height: 200px;
}
/* Select the paragraph that is the first-child of the .block element */
.block p:first-child {
color: red;
}
```
> Note: The pseudo-class gets applied to the element you want to select, not the parent.
### The `:nth-child` Pseudo-class
This is a great pseudo-class for selecting a specific element that does not have a class or ID to identify it. It takes a parameter which is the number of the element you would like to select.
```htmlmixed
<div class="block">
<p>Par one</p>
<p>Par two - this paragraph will be red</p>
<p>Par three</p>
</div>
```
```css
.block {
background: grey;
width: 200px;
height: 200px;
}
.block p:nth-child(2) {
color: red;
}
```
### The `:nth-of-type` Pseudo-class
There is a pseudo-clas that is similar to nth-child called nth-of-type. This class allows you to select a specific element that is of a specific type. The main difference between nth-of-type and nth-child is that nth-of-type does not have to be a child of any element.
This pseudo-class also takes a number as a parameter.
```htmlmixed
<p>Par one</p>
<p>Par two - this paragraph will be red</p>
<p>Par three</p>
```
```css
p:nth-child(2) {
color: red;
}
```
### The `:not` Pseudo-class
What if you want to select a class of elements but not one of the elements in that set? Of course you could set an ID but there is a pseudo-class for that.
This pseudo-class takes a selector as a parameter and it is important to note that you do NOT need quotes for the selector.
```htmlmixed
<div class="block">
<p class="par">Par one</p>
<p class="par not-red">Par two</p>
<p class="par">Par three</p>
</div>
```
```css
.block {
background: grey;
width: 200px;
height: 200px;
}
p:not(.not-red) {
color: red;
}
```
There are many more pseudo-classes of course.
==BOOKMARK THIS==
https://www.w3schools.com/css/css_pseudo_classes.asp
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add a link
3. Change the color of the link to red on hover
4. Add 3 paragraphs
5. Color the first paragraph green
6. Color the second paragraph purple
7. Do not use classes or IDs
8. Name/save project
==KNOWLEDGE CHECK==
1. What is a pseudo-class?
2. What is the difference between nth-child and nth-of-type?
==QUESTIONS?==
---
## Pseudo Elements
A CSS pseudo-element is used to style specified parts of an element.
Syntax
```css
selector::pseudo-element {
property:value;
}
```
> Note: Notice the double colon, not a single colon.
### The `::first-line` Pseudo-element
This pseudo-element allows you to adjust the first line of text which can be useful for emphasis or introductory text.
> Note: It will always be the first line, even if the viewport size changes.
```htmlmixed
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint fugiat necessitatibus consequuntur aspernatur esse, omnis dolorem obcaecati, libero expedita voluptatum, repellendus eos eius explicabo dignissimos natus. Fugiat, quaerat vitae voluptate dolores aliquam, harum iure impedit earum assumenda tempora aut velit eaque repellat consequuntur numquam illo ipsa eveniet dolorem similique odit! Ipsum itaque voluptatem deleniti vitae earum dolore, debitis error autem, distinctio, magni ex minima nemo velit reprehenderit? Accusantium cupiditate, recusandae voluptates dolorum et dignissimos magnam, repellat rerum nemo obcaecati vel. Quidem perferendis soluta, quaerat possimus ex quos? Quibusdam quas odit aliquid dolorum at saepe excepturi, quis, perferendis labore sequi ea!</p>
```
```css
p::first-line {
font-weight: bold;
}
```
### The `::first-letter` Pseudo-element
Very similar to first-line but it only applies to the first letter.
```htmlmixed
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Sint fugiat necessitatibus consequuntur aspernatur esse, omnis dolorem obcaecati.</p>
```
```css
p::first-letter {
font-weight: bold;
color: red;
}
```
### The `::before` Pseudo-element
The `::before` pseudo-element can be used to insert some content before the content of an element. This element uses a content property.
```htmlmixed
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit.</p>
```
```css
p::before {
content: "BEFORE TEXT"
/* You can also use an image or icon or something else */
content: url("...");
}
```
There is an `::after` element that is exactly the same except it appends the content to the end of the element.
==QUESTIONS?==
## Opacity
The opacity property allows you to define the transparency of an element. The values you set can be from 0 to 1 where 0 is completely transparent. Decimals are accepted.
```htmlmixed
<img src="https://images.unsplash.com/photo-1515879218367-8466d910aaa4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" alt="">
```
```css
img {
height: 200px;
width: 200px;
opacity: .3;
}
```
==QUESTIONS?==
---
## Box Sizing
If you remember the box model submodule we covered early in this module you will remember that each element can contain the content, the padding, the border and finally the margin.
The issue is, when the browser calculates the height and width of an element it also adds padding and border to that calculation. That will make the element look larger than intended and lead to unexpected results.
```htmlmixed
<div></div>
```
```css
div {
height: 200px;
width: 200px;
border: 2px solid red;
padding: 50px;
}
```
It is hard to tell now but the 50px of padding is making the div larger than 200 x 200. The easy fix for this is to use box-sizing.
```css
div {
height: 200px;
width: 200px;
border: 2px solid red;
padding: 50px;
box-sizing: border-box;
}
```
> Best Practice: It is recommended to apply border-box to all elements.
Do this somewhere near the top of your stylesheet.
```css
* {
box-sizing: border-box;
}
```
==QUESTIONS?==
---
## Specificity
There is a possiblity that you could have two or more CSS rules pointing to the same element. For that reason the browser needs rules to determine which one should actually be applied to an element.
Take this example:
```htmlmixed
<p class="blue">Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia, illum.</p>
```
```css
p {
color: red;
}
.blue {
color: blue;
}
```
Both selectors are pointing to the same element. So which rule should be used? The paragraph will end up blue because of the specificity hierarchy. They are in this order:
1. Inline - styles attached directly to an element
2. IDs - an element with a unique ID
3. Classes, attributes and pseudo-classes
4. Elements and pseudo-elements - e.g., p, h1, :before/:after
So for example if you have an element with both an ID and a class and use those selectors to style the element, the ID will take precedence because it is higher in the hierarchy.
The higher in the order, the more likely the stling will be applied to the element. There are some rules to calculating specificity but more importantly there is a calculator for that.
==BOOKMARK THIS==
https://specificity.keegan.st/
### Cascading in Cascading Stylesheets
Now would also be a good time to address the word *cascading* in cascading stylesheets. Let's start with an example.
```htmlmixed
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Mollitia, illum.</p>
```
```css
p {
color: blue;
}
p {
color: red;
}
```
In this example the paragraph will end up red because the selectors are the same and the styles cascade from the top down. I know this may seem like an arbitrary example, but it basic to simply show how the cascade effect works. But also to show that your styles can be overwritten if they are not specified in the order you intended.
A more realistic example would be using multiple stylesheets, because you can use as many stylesheets as you want. If you specify 2 of them in the HEAD and they are not referenced in the correct order, you may end up with undesired results.
> Note: Specificity trumps the cascade effect. So even if there are two selectors targeting the same element but one is a higher level of specificity, it will take precendence.
### The `!important` Keyword
There is one keyword that will trump everything. If you use it, the styles are just about guarenteed to be applied.
```css
p {
color: red !important;
}
```
> Best Practice: Because it overrides all other rules, it is a best practice to only use this keyword when absolutely necessary. Styles get very hard to track when you begin using this keyword.
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add 1 paragraph
3. Add 2 rules that both point to that paragraph
4. Use specificity to color the paragraph purple
5. Name/save project
==KNOWLEDGE CHECK==
1. What is specificity?
2. What is the cascade effect?
3. If you referenced 2 stylesheets in the HEAD of your document and each had a rule that targeted the same element, which would be more likely to have their style applied?
4. What is the `!important` keyword?
==QUESTIONS?==
---
## Background
One of the more fun things you can do with CSS is adjust the background of an element, whether it is the color or setting it to an image.
### Background Color
> Note: Any CSS property that has two words will be separated with a dash.
```css
div {
background-color: red;
/* You can also use hex */
background-color: #0080ff;
/* Or rgb */
background-color: rgb(255,0,0);
/* Or rgba - the last value is the opacity, rgba will allow you to adjust the opacity of the bg color*/
background-color: rgba(76, 175, 80, 0.3);
}
```
### Background Image
The `background-image` property takes a url value. The URL techincally does not need quotes but it is a best practice to wrap the value in quotes.
```css
div {
border: 1px solid red;
height: 700px;
width: 100%;
background-image: url(https://www.incimages.com/uploaded_files/image/970x450/software-computer-code-1940x900_35196.jpg);
}
```
As you can see the background image is unable to fill the entire vertically. When that occurs, either vertically or horizontally you will see that the background image repeats by default.
#### Background Repeat
Values:
* repeat - repeat background along both x and y axis
* repeat-y - repeat background along y-axis
* repeat-x - repeat background along x-axis
* no-repeat - disable repeat
* space - repeat as much as possible without clipping. The first and last images are pinned to either side of the element, and whitespace is distributed evenly between the images
* round - repeat and squish or stretch to fill the space (no gaps)
> Note: 90% of the time you will be disabling the repeat function.
```css
border: 1px solid red;
height: 700px;
width: 100%;
background-image: url(https://www.incimages.com/uploaded_files/image/970x450/software-computer-code-1940x900_35196.jpg);
background-repeat: no-repeat;
```
That is better, the background is no longer repeating, however it is not filling the container either. Adjusting the background size will help with that.
#### Background Size
Values:
* auto - default
* length - width/height
* percentage - width/height
* cover - resize to cover the entire container
* contain - make sure all of background image is seen
```css
div {
height: 300px;
width: 100%;
background-image: url(https://www.incimages.com/uploaded_files/image/970x450/software-computer-code-1940x900_35196.jpg);
/* You could do this - but as you adjust the screen size you will see that because the height/width is not dynamic, the image will begin to distort */
background-size: 100% 100%;
/* Cover will keep the dimensions nicely along viewports, although it is not perfect */
background-size: cover;
}
```
As with everything else in CSS, there are a few more background properties that can explore on your own. But those are the most commonly used ones.
#### Background Shorthand
As you can imagine setting all of those values for every background image can get cumbersome. Good news is there is a shorthand for them.
Order:
* background-color
* background-image
* background-repeat
* background-attachment
* background-position
Syntax
```css
background: color image repeat attachment position
```
> Note: Values can be omitted or left out, this does not matter as long as the other values are in order.
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add a div
3. Add a background image (use the shorthand) to the div
4. Make sure the image covers the entire div
5. Make sure the background image does not repeat
6. Add some text to the div
7. Center the text both vertically and horizontally in the div
8. Name/save project
==QUESTIONS?==
---
## Transitions
Sometimes you want to slow down or otherwise adjust the transition of things like say hovering a link or changing the opacity of an element. If the transition property is not set it will always be fast and the user might not get to take full effect of the hover effect.
Take this example:
```htmlmixed
<button>Click Me</button>
```
```css
button {
background: #ccc;
border: 0;
padding: 10px;
margin: 20px;
opacity: .5;
}
button:hover {
opacity: 1;
cursor: pointer;
}
```
The opacity changes so fast it is almost jarring, it could certainly be more elegant and refined. The transition property has 4 properties:
* delay - delay before the effect happens
* duration - how long the effect should last
* property - which CSS property the effect is for
* specify the speed curve
Here is the example with transition:
```css
button {
background: #ccc;
border: 0;
padding: 10px;
margin: 20px;
opacity: .5;
transition-delay: 0;
transition-duration: .4s;
transition-property: opacity;
transition-timing-function: ease-in-out;
}
button:hover {
opacity: 1;
cursor: pointer;
}
```
### Timing Function
Values:
* ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
* linear - specifies a transition effect with the same speed from start to end
* ease-in - specifies a transition effect with a slow start
* ease-out - specifies a transition effect with a slow end
* ease-in-out - specifies a transition effect with a slow start and end
* cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function
### Shorthand
```css
transition: property duration timing-function delay|initial|inherit;
/* Previous example would be written as - delay is omitted */
transition: opacity .4s ease-in-out;
```
==QUESTIONS?==
---
## Animations
One of the best things about CSS is the ability to animate elements! There are two main properties that allow us to create animtions; `@keyframe` and `animation`.
### `@keyframe`
The `@keyframe` is where you define the animation. Both the name and what the animation will be doing.
```css
@keyframes animationName {
/* Method 1 */
from {
/* starting point */
}
to {
/* ending */
}
/* Method 2 */
0% {}
25% {}
50% {}
75% {}
100% {}
/* You can use whatever percentage values you want */
}
```
### Animation
Properties:
* name
* duration
* delay
* iteration-count - how many times you want the animation to run (can use infinite)
* direction - alternate|forward|backward
* timing-function
* fill-mode - specifies a style for the element when the animation is not playing (before it starts, after it ends, or both)
#### Shorthand
```css
animation: name duration timing-function delay iteration-count direction;
```
Lets make an animation!
```css
/* Method 1*/
@keyframes heartbeat {
from {
transform: scale(0.75);
}
to {
transform: scale(1);
}
}
/* Method 2 */
@keyframes heartbeat {
0% {
transform: scale(0.75);
}
25% {
transform: scale(1);
}
50% {
transform: scale(0.75);
}
75% {
transform: scale(1);
}
100% {
transform: scale(0.75);
}
}
button {
animation: heartbeat 3s ease-in-out infinite alternate;
}
```
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create a new PlayCode project
2. Add a div
3. Give the div height/width
4. Create an animation (method 1 OR 2, doesn't matter) to change the background of the image between 2 colors infinitely
5. Set the direction of the animation to alternate
6. Name/save project
==QUESTIONS?==
---
==SWITCH TO HTML/CSS DOCUMENTS==
## Responsive Styling
The is one of the most important aspects of this entire module. As we covered with responsive images, you never know what device size your webpage will be viewed on. With that said you want to make sure you style your site so that it will adjust to any screensize accordingly.
### Setting the Viewport
The first thing you want to do for any webpage is make sure you have the viewport meta tag in the HEAD of your HTML document.
```htmlmixed
<meta name="viewport" content="width=device-width, initial-scale=1.0">
```
That meta tag will tell the browser what size your viewport is. Without it, the browser will not be able to take advantage of responsive styling.
### Responsive Images
When using images you pretty much always want to make sure it is responsive, meaning the height and width will adjust based on the screen size. By default if you add an image and then adjust the screen size, you will see the image will be cut off.
```htmlmixed
<!-- Adjust window size in PlayCode -->
<img src="https://www.elegantthemes.com/blog/wp-content/uploads/2018/04/Best-Code-and-Text-Editors.png" alt="">
```
It is very easy to fix this and make sure the image scales with the viewport size.
```css
img {
max-width: 100%;
height: auto;
}
```
### Responsive Text Size
Another part of responsive styling is the font size. A large font size on desktop may end up being too large when viewed on a phone for example. One way to solve this problems is to use responsive measurement units for the font size.
```htmlmixed
<h1>I am a title</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Saepe quasi tenetur eius? Pariatur perferendis corrupti tenetur est recusandae, cum deleniti!</p>
```
```css
h1 {
font-size: 3vw;
}
p {
font-size: 1vw;
}
```
As you can see the font size will scale as we adjust the window size. However, the font size will begin to get too small eventually. Media queries can help with that!
### Media Queries
Media queries are the cornerstone of responsive web design. Basically they let you adjust the styles of your elements based on the screen size, making the styling dynamic.
#### Syntax
```css
@media mediaType and (mediaFeature: measurement) {
/* Rules for this screen size */
}
```
Media Type:
* all - default
* print - printers
* screen - computer screens, tablets, smart-phones
* speech - screenreaders
Typically you will want to use the *screen* media type or omit the media type value to use the *all* default.
Media Feature:
* min-width
* max-width
There are *a lot* of media features but typically you will use `min-width` or `max-width`.
#### Breakpoints
Responsive styling uses breakpoints to determine when specific styles should kick in. Lets say you set a font size on a header and at 1100px width the font size is too small. At that point you would define a new media query to adjust the font size. That point in which you define a new media query is called a breakpoint.
There are common breakpoints for specific devices such as desktop, iPad, iPad landscape, iPhone 6 and on and on. The problem, as I'm sure you could guess is that there are too many devices and screen sizes to use these with any confidence.
The best practice is to test your webpages and see where it *breaks* and then define your own breakpoint. Afterall, you can have as many media queries and breakpoints as you want.
Basic Breakpoints
* 1200px+ - laptop/desktop
* 768px - tablet
* 600 - mobile
### Example
```htmlmixed
<h1>Title Here</h1>
```
```css
h1 {
font-size: 4vw;
}
/* The max-width means: Start at 600px and use these styles for any device size below 600px or until another breakpoint is found */
@media screen and (max-width: 600px) {
h1 {
font-size: 6vw;
}
}
/* The max-width means: Start at 400px and use these styles for any device size below 400px */
@media screen and (max-width: 400px) {
h1 {
font-size: 8vw;
}
}
```
As you can see, with our two breakpoints (600 and 400), the font size never gets too small.
Notes:
* The order is important
* If you are using max-width you want to order them from the largest on down, which is why we used 600px THEN 400px
* If the breakpoint for 400px was before the breakpoint for 600px, the 400px breakpoint would never be hit
* A best practice is to create a new stylesheet that contains your media queries so they do not clutter up your main stylesheet
* Because of the cascading effect it is recommended to reference your stylesheet containing your media queries BELOW your main stylesheet
### Realistic Example
Let's build a somewhat more realistic example to show what it would really look like to use media queries.
==Build this out (HTML/CSS docs, NOT PlayCode) - do not copy/paste==
```htmlmixed
<div class="container">
<div class="column left">
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates modi, fugiat hic aut minima repellendus quisquam laboriosam iure, excepturi laudantium sed odio, totam culpa autem aliquam voluptate omnis dolore soluta. Autem, quisquam architecto, omnis magnam quam voluptate quas dignissimos perferendis neque aspernatur quibusdam ipsam, dolore dolorum aut explicabo placeat nemo!</p>
</div>
<div class="column right">
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates modi, fugiat hic aut minima repellendus quisquam laboriosam iure, excepturi laudantium sed odio, totam culpa autem aliquam voluptate omnis dolore soluta. Autem, quisquam architecto, omnis magnam quam voluptate quas dignissimos perferendis neque aspernatur quibusdam ipsam, dolore dolorum aut explicabo placeat nemo!</p>
</div>
</div>
```
```css
.container {
background: #ccc;
padding: 20px;
}
.column {
width: 45%;
display: inline-block;
font-family: Helvetica;
line-height: 1.5;
}
.column.left {
margin-right: 5vw;
}
@media screen and (max-width: 600px) {
.column {
width: 100%;
display: block;
}
.column.left {
margin-right: 0;
}
}
```
### Combination Media Queries
If you, for example, notice that you webpage has some sort of styling issue but it only occurs on mobile device when in landscape mode, you can target that as well by combining media queries. Simply separate the queries with *and*.
```css
@media screen and (max-width : 768px) and (orientation : landscape) {
/* Styles */
}
```
There are a lot of possible media query combinations and types, but max-width and min-width usually work for most scenarios. If you happen to need a more advanced query, a quick Google search will typically get you what you need.
==EXERCISE==
> Place in chat
> Have them share their screen
1. Create HTML/CSS documents
2. Also create a responsive.css file
3. Recreate this 
4. Make sure the columns stack on mobile (600px or below)
==KNOWLEDGE CHECK==
1. What is a breakpoint?
2. When should you define a breakpoint?
3. How many media queries are you allowed to use?
==QUESTIONS?==
---
## Cross Browser Testing
Now that we are coming to the end of the CSS module it is time to discuss browser support and testing. Just as your webpage may look different across different screen sizes, it can also look and perform different across web browsers. The primary reason is that each web browser will support different CSS features and properties, compatibility is not guarenteed across all browsers.
Testing Methods
* Manual
* Automated
### Manual Testing
With this method you essentially open your webpage in every browser than you can and check for bugs or inconsistencies. So if you have Google Chrome and Mozilla Firefox installed, maybe install Opera and Edge if possible and test in all of those browsers.
Of course if you are on Mac you will not have Microsoft Edge (a Windows browser) and if you are on Windows you will not have Safari (which is a Mac browser). That said, the second method - automated testing, is a more thorough option.
### Automated Testing
Automated testing allows you to test multiple devices and operating systems at the same time, which saves time and effort. There are plenty of tools available online for cross-browser testing. Some are paid and some are free. If you are orking for a company there is a good chance they will provide you with access to a cross-browser testing tool.
Let's look at Lambdatest which offers a free plan:
==DEMO BROWSER TESTING==
[CLICK HERE](https://app.lambdatest.com/console/realtime)
### CSS Reset
As we discussed early on, each browser will apply their own styles. This, of course, will cause inconsistencies. One way to reduce cross-browser issues right out of the gate is to use a CSS Reset. The goal of a reset stylesheet is to reduce browser inconsistencies in things like default line heights, margins and font sizes of headings, and so on.
A popular CSS Reset is [Eric Meyer's Reset CSS.](https://meyerweb.com/eric/tools/css/reset/) (BOOKMARK THIS)
Simply copy and paste it into the very top of your main stylesheet or create a new reset.css stylesheet and make sure it is the first stylesheeet you reference in the HEAD.
==SHOW USER THE DIFFERENCE IN PLAYCODE==
### Browser Support
So what do you do when you DO discover an issue that only exists in one browser or another?
* Inspect the element where the issue exists
* Check [CanIUse](https://caniuse.com/) (student -> BOOKMARK THIS)
* This site will let you know which browser versions support the property you are investigating
If you check CanIUse and determine that a browser or browser version does not support a CSS feature, the next step would be to see if there is a browser-prefix available.
### Browser Prefixes
Browser prefixes are used to add new CSS features to a browser that does not support them natively. There are four primary prefixes:
* -webkit- (Chrome, Safari, newer versions of Opera, almost all iOS browsers including Firefox for iOS; basically, any WebKit based browser)
* -moz- (Firefox)
* -o- (Opera)
* -ms- (Internet Explorer and Microsoft Edge)
If a prefix exists it is common practice to use all four prefixes to cover all your bases.
Usage:
```css
p {
-webkit-transition: all 4s ease;
-moz-transition: all 4s ease;
-ms-transition: all 4s ease;
-o-transition: all 4s ease;
transition: all 4s ease;
}
```
To check if a browser prefix is available go to [Autoprefixer](https://autoprefixer.github.io/) (student -> BOOKMARK THIS), then type in the problematic property. If a prefix is available, type in the rule in the left side like this:
```css
transition: all 3s linear;
```
Autoprefixer will add the appropriate prefixes to your code. You can also copy and paste your entire stylesheet in the left side and Autoprefixer will add all the available prefixes for you to ensure the best browser support.
> Sidenote: Nowadays this process is not really necessary. When you eventually get around to using a task runner such as Gulp or Webpack it will add the prefixes for you when when it builds your project. But for now it is a good idea to use Autoprefixer to get used to including vendor prefixes.
==KNOWLEDGE CHECK==
1. What is cross browser testing?
2. How do you test multiple browsers?
3. If you discover an issue that only exists in one browser, what do you do?
==QUESTIONS?==
---
## MODULE PROJECT
REQUIREMENTS
1. DO NOT recreate device frames
2. Recreate desktop layout below
3. Must match mobile layout (below) for screens less than 600px
4. At least 1 web font (downloaded)
5. At least 3 icons (from CDN)
6. Hover state (of your choice) must exist for all links
7. Stylesheets must be external (main, responsive)
8. CSS reset must be present (at top of main stylesheet or in its own stylesheet)
9. Hero image (top of page) must be a background image
10. Use transform to vertically AND horizontally center text over hero image (top of page)
11. Styling must be consistent across all browsers
12. Hide navigation links on mobile (<=600px)
Feel free to be creative! The images you use or colors, that is all up to you.
RESOURCES
* https://unsplash.com/
* https://fonts.google.com/
* https://ionicons.com/v1/
DUE: 1 week

