Coding - Intro To CSS

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Intro to htmL

- Stands for HyperText Markup Language


o Markup language: Computer Language – define structure and presentation of a
webpage
o HyperText: text on devices/computer: provides access to other text via links (hyperlink)
- Html is the skeleton of all webpage – it provides structure to content
WHAT DO YOU NEED TO KNOW:
- Structure/folder needed:
o Index.html: the original file. Clicking on this will land on the homepage
o Image folder: contain all the image of website
o Styles folder: contain all the css code used to style for your website
o Script folder: contain all the JavaScript code used to give interaction for your website.
- General file path rule:
o Same level (folder) link: use the file name with extension
o Lower level (folder) link: use the subfoldername/filename or ./filename
o Upper level (folder) link: use ../filename
o Can combine these path together
1. Anatomy of an element:
- Ex: <p>Hello</p>
- Composed of an opening tag – content – closing tag – in exact order
- Element = 1 unit of content
- Tag = opening bracket – element name – closing bracket
o Opening tag = the tag to start an element <tag name>
o Closing tag = the tag to close an element </tag name>
2. Body: key element to build webpages
- Structure: <body>content</body>
- Can add text, image, button into the body
3. Structure: child/nested/parent
- An element (1) contains another element (2)
o (1) parent
o (2) child
o 2 is nested in 1
4. Heading:
- Structure: <h1></h1> to <h6></h6>
- Ranging from the largest to smallest in size (h1 to h6)
5. Division (div) and span (span)
- Division: <div></div>
o A container that divides the page into sections
o Add a tab (2 spacebars) with a child nested in divs
o Use div as a container for other html element to style with
- Span: <span></span>
o Contain short pieces of text or another html
o Separate small pcs of content on the same line as other
o Same function as <div> but for inline element
o Use span as a container for other html element to style inline
6. Attributes
- Are extra content that added to the opening tag
- Provide information/change the style of the element
- Two parts of attributes:
o Name of attributes
o Value of attributes
o Ex: <div class=”intro”>
- An example of common attribute: id – specify a content
o Ex: <div id=”intro”>content</div>

7. Displaying text
- Paragraph: <p></p>
- Contain a block of plain text
8. Styling text:
- Use tag within element: emphasize and strong
o Emphasize: give an italic text <em></em>
o Strong: give a bold text <strong></strong>
- Emphasize and strong tell the html how important the text is
9. Line break <br>
- Is a self closed tag
- Make a line in you text
- Put before the start word of the line
- 1 <br>=1 line
10. Unordered list <ul></ul>
- To create a list of item in no order
- <ul></ul> should not contain any raw text
- List items in bullet points
- Every single item stays between <li></li> tag, each item has 1 <li></li> tag
11. Ordered list
- Same as <ul></ul>, but items are listed in number points
- Coding element: <ol></ol>
12. Image
- Allows you to insert image into your tag
- Is a self-closing tag
- Code: <img src=”link”/> (basic)
- Special img alt: <img src=”link” alt=’content’/>
o Provide description in case of failure to load
o Help with visually impaired user
o Improve ranking webpage through SEO tool
13. Videos
- Tag: <video src=”link” width=”number” height=”number” controls> text </video>
HTML DOCUMENT STANDARD

1. Preparing for html


- Starting document with html declaration: <!DOCTYPE html>
- Standard environment for running code: html5
- The declaration will let your browser know you using html
- The code text will be saved with .html extension
2. Html tag:
- Add html structure to content
- Code syntax: <html></html>
- Without html tag: the browser can incorrectly interpret your code
3. Head tag: <head></head>
- Give browser information about the webpage itself
- Contains the metadata for a webpage (information about the page itself)
4. Page titles <title></title>
- Displays the title in the title tag for a browser’s tab
- Always inside the <head></head> tag
o Ex: <!DOCTYPE> <html> <title> content </title> </head>
<body> content </body> </html>
5. Link to other webpage: anchor tag: <a></a>
- Code: <a href =”link”> the text under the link </a>
- To open link in a new window:
o Target: the attribute to determine how your link should be open
o New window: target=”_blank”
- Code: <a href=”link” target=”_blank”> text </a>
- Link to a relative path:
-
Intro to CSS

- HTML = the skeleton of webpage; CSS (Cascading Style Sheets) = create style for HTML webpage.
- Modifying colors, font types, font sizes, shadows, images, element positioning..
- Extension: .css
o Save in a different file other than .html file
o Can write all the css code needed to style a page
1. Inline style
- Can write CSS code within HTML code using inline style
- Attribute: style=”..;” – always end with a semicolon “;” after every component
o Ex: <p style=”color: red;”>I’m learning to code!</p>
 Result: I’m learning to code!
- A quick way of directly styling an HTML element
o Ex: <p style=”color: red; font-size: 20px;”>I’m learning to code!</p>
 Result: I’m learning to code
2. The style tag <style></style>
- Css code can be written between <style></style> tag
- To use <style> tag, it must be placed inside of the <head> tag
- The code will follow the same rules with inline tag
o Ex: <head><style> p {color: red; font-size: 20px;} </style></head>
3. Linking the .css file
- Using <link> element to link html and css together. It is a self-closing tag
- Must be placed within the head of html file
- Attributes:
o Href: the address or path to css file
o Type: the type of document linking to (.css). should be set to text/css
o Rel: the relationship between html file and css file. Should be set to stylesheet.
 Ex: <link href=”url link to file” type=”text/css” rel=”stylesheet”>
 Ex: <link href=”./style.css” type=”text/css” rel=”stylesheet”> - link to file on
relative path
4. Tag name
- Using element’s tag name: css can select html element
- The syntax for selecting element:
o p{
}
o it will style the paragraph element
o any css properties will go inside curly braces to style the selected elements
 ex: h1 {color: maroon;}
5. Class name:
- Css can also style element by attributes (class)
- Ex: <p class=”brand”>Sole Shoe Company</p>
In css: .brand {…}
- To select element for styling using attributes: .attribute name
- By running style over class name it will overrun any tag element – make the style more specific
to just one class, not the whole tag element
- Select multiple class:
o To add more than one class name to html element’s class attribute:
 Write two css rules for styling
 Ex: .green {color: green;} .bold {font-weight: bold;}
 Include both of those classes on one html element, separated by a spacebar:
 <h1 class=”green bold”>…</h1>
o In this way we can create unique style for element without writing custom class for
every style.
6. ID name:
- Styling multiple class is used to combine different style in one element (every style is separated
in one syntax. Classes are not unique.
- Styling id is used to create an unique style to one group of element. Ids are unique
- How to style id:
o Find an id to style. Ex: <h1 id=”large-title”>..</h1>
o Add id attribute on css. Ex: #large-title {..}
o Id tag in css always attached with #
- Id will override the style of tags and classes
7. The order of style priorities:
- Best practice: style elements first so that you can override if changes needed.
- Order of priorities: ID>classes>tags
8. Chaining selectors:
- Used when there is the same class on two different elements. Ex: class=”special” on <p> and
<h1>
- To select specific class on element: on css: name-of-element.class-name
o Ex: h1.special {..}
9. Styling nested elements
- Syntax: .class-name element-nested-in (space is given in between)
- It will style all the specific elements nested in a class
o Ex: .description h5 {..} will style all the h5 header in class description
- Order of priority: nested element styling>element styling
10. Important code - !important
- Can be applied to specific attributes instead of full rule
- Will override any style no matter how specific
- Syntax: p {color: blue !important;} .main p{color: red;}
o Will rule out any other styling effect
o Best to avoid and use at last resort
11. Multiple selector:
- Prevent repetitive code if both have same style
- Code: element , element {..}
o Ex: h1, .menu {font-family: Georgia;}
12. CSS structure:
- Ex: h1 {color: blue;} – CSS declaration
- Css declaration = Property + value
o Property: the property you want to style of an element
o Value: the value of property
13. Property:
- Font family
o The specified font must be installed on a user’s computer in order for display
o The default typeface: times new roman
o Limit the number of typeface: 2 to 3
 Help page load faster
 A good design
o Put in quotes if font name is more than 1 word
o Code: font-family: name of font;
o Web safe font: https://www.cssfontstack.com/
- Font size:
o Code: font-size: (number)px;
- Font weight:
o Code: font-weight: value;
o Value:
 lighter<normal<bolder<bold
 100 to 900
 400: normal font-weight
 700: bold font-weight
 300: light font-weight
- Text align
o Code: text-align: value;
o Value: left, center, right
- Color:
o Foreground color (property: color): the color that an element appears in
o Background color (property: background-color): the color that an element is covered in
- Opacity:
o Measure how transparent an element is
o Value: 0 to 1
- Background image:
o Set the element’s background to display an image.
o Code: background-image: url(“link”);
o Or: link to a relative path: background-image: url(“folder/filename.jpg”)

THE BOX MODEL

1. The model:
- Comprises the set of properties defining part of an element taking up space on a webpage:
o Width and height: specifies the width and height of the content area
o Padding: the amount of space between the content area and the border
o Border: the thickness and style of border surrounding the content area and padding
o Margin: the amount of space between the border and outside edge of element

2. Height and width


- An element content area = height and width
- By default: the dimensions of html box are set to hold the raw content of the box
o Property: height/width
o Value: (number)px
 Ex: height: 20px; width: 30px;
3. Borders:
- Border: a line surrounding an element – like frame around a painting. Border can be set with:
o Width: the thickness of the border
 Value: in (number)px or keywords: thin, medium, think
o style: the design of border.
 Value: none, dotted, solid
 View reference to style here: https://developer.mozilla.org/en-
US/docs/Web/CSS/border-style#Values
o Color: color of the border
 Value: over 140 built-in color keywords: https://developer.mozilla.org/en-
US/docs/Web/CSS/color_value
o Code syntax: border: (width value) (style value) (color value);
 Ex: border: 20px dotted cyan;
- The default border style: medium none (color) – the color is the color of the background
- Border radius:
o Default: it will be squared
o Modify the corner of an element’s border box:
 Property: border-radius
 Value: (number)px
 Ex: border-radius: 5px;
o Will set all four corners of a border to a radius of 5px
o Can create a perfect circle border: value=height of the box; or value=100%
4. Padding
- Is the space between the contents of a box and the borders of a box – in another word: add the
space inside the element
o Property: padding
o Value: (number)px
 Ex: padding: 10px;
o If you want to be more specific:
 Padding-top
 Padding-right
 Padding-bottom
 Padding-left
- Another way to pad on each side at the same time:
o Padding: top right bottom left;
 Ex: padding: 6px 11px 4px 9px;
o Must pad to all four side in the code
o Or use the shortcut to set the equal side: padding: top-bottom left-right;
 Ex: padding: 6px 11px; - will pad 6px top and bottom and 11px left and right
5. Margin:
- The space directly outside of the box – in another word: add the space around the element
o Property: margin
o Value: (number)px
- Be more specific:
o Margin-top
o Margin-bottom
o Margin-right
o Margin-left
- Simpler implementation: margin: top right bottom left;
o Must have all four sides
o Shortcut: margin: top-bottom left-right;
- Auto: use to center content and element
o Code syntax: margin: (number)px auto;
 The first number will determine top and bottom margin
 Auto will adjust the content to be in the center
o BUT it must have the width of the content
 Ex: div.headline {width: 400px; margin: 0 auto;}
 The width will be set to 400px and the div will be centered (once it has the
width of the content – element)
- Margin collapse:
o The left and right margin will collapse – the space between two element = the sum of
margin on adjacent side
o The top and bottom margin will not collapse – the space between two element will be
determined by the higher number

6. Minimum and maximum height and width


- Min-width: ensure a min width of an element box
- Max-width: ensure a max width of an element box
- Min-height: ensure a min height of an element box
- Max-height: ensure a max height of an element box
o Value: (number)px;
- Text will overflow if the width and height are not enough to contain a text piece
7. Overflow
- To ensure that all element is within readability: use overflow
- Control what happens to content that spills outside its box
o Property: overflow
o Value: visible (default – will display outside of the containing element), hidden (overflow
content will be hidden), scroll (a scrollbar will be added to the content)
8. Resetting defaults:
- In the absence of an external stylesheet: use default stylesheet (user agent stylesheet)
- User agent stylesheets: have default css rules for padding and margin
- To reset the default value:
o Margin: 0;
o Padding: 0;
 If measurement = 0: do not require unit
9. Visibility:
- Element can be hidden from view with the visibility property
- How to set up:
o Property: visibility
o Value: hidden – hides an element; visible – displays an element
- If visibility: hidden; : the content will be hidden, but the space will not !== display: none; :
completely removed from the webpage

THE NEED TO CHANGE BOX MODEL: if you modify all the border, height, width, padding, the total
dimensions will be messed up. It will be difficult to accurately size a box, makes it difficult to position
and manage

1. Box model: content-box


- The box-sizing property: control the type of box model the browser should use
- The box-sizing default value: content-box – see img below
2. Box model: Border-box
- Ex: box-sizing: border-box;
- It will reset the box model to border-box for all html element, avoid dimensional issues
o The height and width of the box remain fixed
o The border thickness and padding will be included inside the box
The overall dimensions will not change
THE UNIVERSAL SELECTOR: * - WILL TARGET ALL ELEMENTS ON THE PAGE

CSS DISPLAY AND POSITIONING

1. The flow of html:


- With html document with no css: a browser will render the elements from left to right, top to
bottom
- Five properties for adjusting the position of html elements:
o Position
o Display
o Z-index
o Float
o Clear
2. Position:
- Block-level element: create a block full width of their parent elements/prevent other elements
from appearing in the same horizontal space.
- Default position for an element: left side of the browser. Can change the position by:
o Property: position
o Value:
 Static: the default value (don’t need to be specified)
 Relative
 Absolute
 Fixed
- Position: relative:
o Allows you to position an element relative to its default static position on the web page
o REMEMBER: need to have the four offset properties to determine the position of where
it is compared relative to – and write them on a different line on the css code page
 Top: move the element down
 Bottom: move the element up
 Left: move the element right
 Right: move the element left
- Position: absolute:
o When position is set to absolute: all other elements on the page will ignore the element
and act like the absolute element is not present on the page.
o The element will be positioned relative to its closest positioned parent element
 Ex: <div class=”box”></div>
 <div class=”cup”></div>
 .cup { position: absolute; top: 20px; left: 50px;}
 This will position the “cup” relatively to “box” class. In particular: move “cup”
block down 20px and to the right 50px from the “box” block
o Absolute position will set the block to scroll when user scroll the page
- Position: fixed
o You can fix and element to a specific position on the page by setting the position value
to fixed: the block will set fixed on the screen no matter where user scrolls on the page
o This is often used on navigation bar
3. Z-index:
- When boxes/blocks have different positions styling: the boxes/blocks can overlap with each
other.
- The z-index controls how far back and forward an element should appear on the page when
elements overlap. Could be understand as the depth of elements: deeper elements appearing
behind shallower element
o Property: z-index
o Value: integer numbers only
 Greater number: will appear in front of smaller number elements
- Z-index does not work on static element
4. Display:
- Inline display:
o For every element: has a default display value: points out if it can share horizontal space
with other elements. Options are:
 Fill the entire browser from left to right
 Only take up as much horizontal space as the content requires – so that it can
be directly next to other elements
o Inline display:
 Ex: <em></em>, <strong></strong>, <a></a>
 Create a box wraps tightly around the element – take only the amount of space
needed to contain that content
 Cannot be altered in size with height or width
 The css inline display:
 Property: display
 Value: inline
 Make any element an inline element – include elements that are not
inline by default: <p></p>, <div></div>, <h1-6></h1-6>
 Ex: h1 {display: inline;} – will change the display of all <h1> to inline –
the browser will render h1 elements on the same line as other inline
elements before or after them
o Block display:
 Some elements are not displayed in the same line as the content around them:
 Ex: <h1-6></h1-6>, <p></p>, <div></div>
 Block display will separate an element to a different line from other element,
and set optionally the width property. Unless specified: the height is determined
to necessary accommodating the content
 Property: display
 Value: block
o Ex: strong {display: block;} – all the strong element will have
own line
o Inline-block display:
 Combines both inline and block element.
 The elements can appear next to each other on the same line and can specify
dimensions using the width and height
 Images are best example of inline block elements
 Property: display
 Value: inline-block
5. Float:
- Use to move an element as far left or far right as possible.
o Property: float
o Value: left/right
- Works for static and relative positioned elements
- MUST have width specified – otherwise: the element will assume the full width of containing
element
6. Clear:
- When float multiple elements: items have different height so they can bump into each other and
affect the layout of the page.
- The clear property will specify how element should behave when they bump into each other
o Property: clear
o Value:
 Left: The left side of the element will not touch any other element within the
same containing element
 Right: the right side of the element will not touch any other element within the
same containing element
 Both: neither side of the element will touch any other element within the same
containing element
 None: the element can touch either side

COLOR IN CSS

- Three types of colors used in css:


o Named colors: keyword colors, can be used directly in css
o Rgb: numeric values describing a mix of red, green and blue
o Hsl: numeric values describing a mix of hue, saturation and lightness
1. Foreground and background
- Foreground: the color of an element
o Property: color
- Background color: the color of the background of an element
o Property: background-color
2. Hexadecimal:
- Is one syntax to specify colors: hex color
- Begin with hash character, followed by 3 to 6 character – represent for red, blue, green
o Number: from 0 to 9; letter: A to F
o Syntax: #ABD183
 DarkSeaGreen: #8FBC8F
 Sienna: #A0522D
 SaddleBrown: #8B4513
 Brown: #A52A2A
 Black: #000000 or #000
 White: #FFFFFF or #FFF
 Aqua: #00FFFF or #0FF
3. RGB color:
- Using numbers describe red green and blue values:
o Property: color
o Value: rgb(x, y, z)
o X, y, z range from 0 to 255
4. Hsl
- Code syntax:
o Hsl(x, y, z)
o X represents the degree of the hue, range from 0 to 360 – refers to an angle on the color
wheel
o Y represents the intensity or purity of the color. Increases towards 100%
o Z represents how light or dark the color is. 50% is normal lightness. 100% makes it
lighter and 0% makes it darker
5. Opacity and alpha
- Opacity: the amount of transparency in color
o Property: hsla
o Values: x, y, z, w
o W is the alpha – the decimal number from zero to one. Zero: transparent; one: opaque;
half-transparent: 0.5
- The alpha can be put in rgb, but not to hex color (rgba)
- For zero opacity color:
o Color: transparent; = rgba(0, 0, 0, 0)

CSS TYPOGRAPHY

1. Font Family
- Type of font: typeface or font family
- Property: font-family
- Note:
o The used font must be installed on a user’s computer
o The default typeface: times new roman
o Good practice: used between: 2 or 3
o When more than 1 word: used between double quotes
2. Font weight:
- Styling bold text with font-weight property:
- Property: font-weight
- Value:
o Default: normal
o Bold
3. Font-style:
- Property: font-style
- Value:
o Default: normal
o Italic
o Oblique
4. Word spacing:
- Increase the spacing between words in a body of text
o Note the difference with letter-spacing; the spacing between characters
- Property: word-spacing
- Value:
o Default: 0.25em
o Value (number)em
5. Letter spacing:
- Increasing the spacing between individual letters
- Technical tern: kerning
- Property: letter-spacing
- Value: (number)em
6. Text transform:
- Change the appearance of a text (uppercase, lowercase, capitalize)
- Property: text-transform
- Value:
o Uppercase
o Lowercase
o Capitalize
- Transform the original text in html to match the intention and readability
7. Text align
- Property: text-align
- Value:
o Left
o Center
o Right
8. Line height anatomy:

-
- Line-height property: modifies the leading of text
- Set how tall we want the line containing our text to be, regardless the height of the text
o Property: line-height
o Value:
 A unitless number: ex: 1.2: an absolute value: will compute the line height as a
ratio of the font size
 A number specified by unit: ex: 12px – can be any valid css unit (px, %, em, rem)
 Preferred value: unitless ratio
9. Serif and sans serif
- Serif: fonts having extra details on the ends of each letter
- Sans serif: fonts do not have extra details on the end of each letter – straight, flat edges
10. Fallback fonts:
- Are pre-installed fonts that falls back if a font is not installed on a computer
- Syntax: font-family: “Garamond”, “Times”, serif;
o All determined elements: Garamond font
o If Garamond not available: times font
o If times not available: use any serif font pre-installed on computer
11. Linking font with google font:
- Go to fonts.google.com
- Search for the font needed
- Select that font with the plus sign
- Drop on the details line
- Embed: standard: to embed the selected fonts into a webpage, copy the code into the
<head></head> of html documents then you can use that
- To import into <style></style> tag: go to @import and copy the code
- To specify the link into css code: copy the css rules to font family
- You can choose all the customization for the font in the customize menu
THE CODE SYNTAX FOR HTML STYLEPAGE: use the <link> tag (selfclosed tag)
- A single linked font: <link href=”https://fonts.googleapis.com/css?family=Droid+Serif”
type=”text/css” rel=”stylesheet”>
- Multiple linked fonts: <link href=”https://fonts.googleapis.com/css?family=Droid+Serif|
Playfair+Display” type=”text/css” rel=”stylesheet”>
- Multiple linked fonts with weights and styles: <link href=”https://fonts.googleapis.com/css?
family=Droid+Serif:400,700,700i|Playfair+Display:400,700,900i” rel=”stylesheet”>
12. Font face
- Font face is another way to link non-user fonts that don’t require the use of <link> tag in html
document
- To load fonts with font face property: (@font-face)
o Enter the link into the url bar in the browser
o The browser will add the css rules.
o Focus on the rules that are directedly label as /*latin*/
o If doing the webpage in other language, focus on that as well
o Copy each of the css rules labeled in latin, and paste the rules from the browser to the
top of style.css
- To add a local font file by using @font-face
o Ex: @font-face {font-family: “Roboto”; src: url(fonts/Roboto.woff2) format(‘woff2’),
url(fonts/Roboto.woff) format(‘woff’), url(fonts/Roboto.tff) format(‘truetype’);}
o The main difference: the use of a relative filepath, instead of a web url
o Add a format for each file to specify which font to use. Since different browsers support
different font types files, so multiple font file options will support more browsers

CSS TIPS AND TRICKS:

- Use classes when you have elements that share many similar characteristics
- Use an id when you have one element that has unique characteristics
- Keep your code dry (don’t repeat yourself)
- Double check your syntax: always end declarations with semicolon, and check that properties
exist

SIZING ELEMENTS

1. Em – based on the parent element


- Em is incorporating relative sizing starts by using units other than pixels. Em in css represents
the size of the base font being used
o Ex: base font: 16px (default size font) => 1em=16px; 2em=32px
- Nested element: default font size based on parent element
2. Rem – based on the root element <html>
- Is another relative unit of measurements. Coded as rem
- Stands for root em – similar to em but check the font size of the root element
- The root element: <html></html> tag
- Default font size for html: 16px; but you can customize that:
o In css: html {font-size: 20px;}
- The advantage of using rem: all elements are compared to the same font size, easy to predict
how large or small will appear
- Rem: sizing elements consistently across an entire website.
- Em: sizing the elements in comparison to other elements
3. Percentages: height and width – sized based on the dimension of parent element
- Use percentages to size non-text html elements relative to their parent elements on the page
- Used to size box-model values: width and height, padding, border, and margins.
- They can be used to set positioning properties (top, bottom, left, right)
- The nested element can be sized relatively with the parent element on the page
- MUST set first the size of parent element
- NOTE: since the box model includes padding, borders and margins, setting an element width to
100% may cause content to overflow its parent container. So 100% should only be used when
content will not have padding, border, or margin
4. Percentages: padding and margin – sized based on the width of parent element
- Can use percentage to set the padding and margin of element
- The calculation works only on the width of the parent element
o Ex: margin-left: 50% for an element: it will move halfway to the right in the parent
container, not the margin getting half of its parent’s margin
- Vertical padding and margin are also calculated based on the width of the parent, since an unset
height of the parent element results in a constantly changing height due to changes to the child
element. Ex:
o A container <div> is defined, with unset height (flat)
o <div> has child <p> nested in. <p> has content and a set height so the height of <div> is
stretched to that height
o <p> changed, resulting in <div> height changed.
- Will calculate the width of the element, then see the height of parent changed due to the
change in the designated element, then modify vertical padding and margin based on that.

***NOTE: ems and rems should be used to size text and dimensions on the page related to text size,
resulting in consistent layout based on text size. Else: use percentages.

5. Width: minimum and maximum


- Adv of relative measurements: provide consistent layouts across devices of different screen
sizes
- Dis-adv: elements on a website can lose their integrity when they become too small or too large.
- To modify the max and min width of a content:
o Min-width
o Max-width
- These will ensure the content is legible by limiting the minimum and maximum width. Should
use the hard measurement (pixel)
6. Height: minimum and maximum:
- Limit the minimum and maximum height of an element
o Min-height
o Max-height
7. Scaling images and videos
- It is important that media in the website is scaled proportionally. Example
o .container {width: 50%; height: 200px; overflow: hidden;}
o .container img {max-width: 100%; height: auto; display: block;}
- Container: width half of the browser width; 200px height. Overflow: hidden to ensure any
overflow content will be hidden from view.
- The image in container: height: auto to automatically scale proportionally with the width. The
display property will prevent images to be in the same line with any other elements in the group
- In the event of the image or media is larger than the container: the vertical or horizontal portion
of the image will overflow to other elements of the container.
o Solution: set max-height: 100% and width: auto. It will scale the height of the image to
the height of the container and the width will be proportionate to the height
8. Scaling background images
- Rule set:

Property Value Meaning


Background-image url(“#”); (the pound key is to Set the background image
refer the source/url of image)
Background-repeat No-repeat; Instruct the css compiler not to repeat the
image
Background-position Center; Centers the image within the element
Background-size Cover; Scales the background of the element. Cover
will make the image cover the entire
background of the element and keep the
image in proportion. If the dimension
exceed, only partial of the image is displayed
CSS BACKGROUND VALUE

Property Value Meaning


Background-repeat (one value syntax: one value will determine for horizontal and vertical axes)
Repeat The image is repeated as much as needed to cover the whole background image painting
area. The last image will be clipped if doesn’t fit
Space The image is repeated 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
image. The background-position property is ignored unless only one image can be
displayed without clipping. The only case where clipping happens using space is when
there isn’t enough room to display one image
Round As the allowed space increase in size, the repeated image will stretch (leaving no gaps)
until there is room (space left >= half of the image width) for another one to be added.
When the next image is added, all of the current ones compress to allow room. Ex: an
image with og width of 260px, repeated 3 times, might stretch until each repetition is
300px wide, then another image will be added. They will then compress to 225px.
No-repeat The image is not repeated (and hence the background image painting area will not
necessarily be entirely covered). The position of the non-repeated background image is
defined by the background-position.
Background-repeat (two value syntax: horizontal axis | vertical axis), can use one value syntax to do this
Repeat-x Repeat | No-repeat
Repeat-y No-repeat | Repeat
Repeat Repeat | Repeat
Space Space | Space
Round Round | Round
No-repeat No-repeat | No-repeat

- Background-position: can use these values: top – left – bottom – right to specify the edge you
want to position your background. The values defines an x/y coordinate, to place an item
relative to the edges of an element’s box. It can be defined using one or two values. If two
values are used, the first value represents the horizontal position and the second represents the
vertical position. If only one value is specified, the second value is assumed to be center.
o 1-value syntax could be:
 Keyword value: center: which centers the image
 One of the keyword values: top, left, bottom, right. This specifies an edge
against which to place the item. The other dimension is then set to 50%, so the
item is placed in the middle of the edge specified.
 A length (pixel) or percentage (%). This specifies the X coordinate relative to the
left edge, with the Y coordinate set to 50%
o 2-value syntax: one defines X and the other defines Y
 One of the keyword values: top, left, bottom, right. If left/right is given: this
defines X and the other given value defines Y. if top/bottom is given: this defines
Y and the other value defines X
 A length (pixel) or percentage (%). If left/right is given: this value defines Y,
relative to the top edge. If top/bottom is given: this value defines X, relative to
the left edge.
- References: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

MEDIA QUERIES

CSS uses media queries to adapt a website’s content to different screen sizes. With media queries, css
can detect the size of the current screen and apply different css styles depending on the width of the
screen. Example:

@media only screen and (max-width: 480px) {body {font-size: 12px;}}


- This media query defines a rule for screens smaller than 480px:
o @media: begins a media query rule and instructs the css compiler on how to parse the
rest of the rule
o

-
- JavaScript methods are actions that can be performed on objects. A JavaScript method is a
property containing a function definition (follow camel casing)
- JavaScript operators are used to assign values, compare value, perform arithmetic operations
- JavaScript objects are standalone entities, with properties and type. (capital first letter)
1. Console
- Is a panel that displays important message
- Method: .log will print out all the information on the parenthesis
- Console is an object (a collection of data and actions)
o The log method will print to the object
o Code syntax: console.log(data);
2. Input comment:
- Single line comment:
o //comment over here: can use inline of the code
- Multiple line comment:
o /*comment*/: can use in between line of code
3. Data type in javascript
- Number: any kind of number
- String: any groups of characters. Must be in single or double quotes
- Boolean: there are only two values for this: true/false
- Null: represent the intentional absence of value. Keyword: null
- Undefined: denoted by undefined, also represent the absence of value – but different from
null
- Symbol
- Object: collections of related data
 The first 6 data type: primitive data types
4. Arithmetic Operator
- Operator: a code/character that performs task in our code.
- Arithmetic operator: code:
o Add +
o Subtract -
o Multiply *
o Divide /
o Remainder/modulo %
5. String concatenation
- Use “+” to add two string (it will add exactly what is on two strings)
6. Properties
- When you introduce a new piece of data: the program will save it as an instance of data
type
- Every string has a property called length
o To check length: console.log(“hey”.length); //output: 5
- “.length” is one of the dot operator
7. Method:
- Are actions that we can perform
o The string method: are actions that we can perform with strings
- Use the dot operator to write a method
o Ex: console.log() = the log method on console object
- Example of string method:
o .toUpperCase() = returns all value/string in capital
o .startWith(“value”) = returns Boolean value (check to see if the string start with a
defined letter
o .trim() = remove all white space at the beginning and end of the string
8. Built-in object:
- Math object is one of the built in object for JavaScript
- Have method for object. Ex: Objectname.log() = print the string in object
- Method with Math object:
o .random() = pick a random number from 0 to 1
o .floor() = round down a decimal number to the nearest whole number
o .ceil() = round up a decimal number to the nearest whole number
o .isInteger() = check if a number is integer or not

VARIABLES

- A variables is a container for value (information)


- Provide a way of labeling data with descriptive name
- Things you can do with data and variables:
o Create variable with descriptive name
o Store and update information stored in a variable
o Reference and get information stored in a variable
1. Create a variable:
- Keyword to use: var/let/const
o Ex: var myName = “ds”;
Console.log(myName); output: ds
- Var will declare variables
- Var name: follow camel casing:
o First word: all lowercase
o Every word after: uppercase first letter
- “=” : assignment operator
- General name rules:
o Can not start with number
o Case sensitive
o Can not be the same name with key words
- Code syntax for var: var varName = “value”;
2. Create variables: with let
- Code syntax: let varName = “value”;
- The variable can be reassigned a different value
- Can use let to declare a variable with no value; the value will be undefined
o Code syntax: let userName;
3. Create variable: const
- Code syntax: const varName = “value”;
- Const var can not be reassigned
- If try: TypeError message
- Const must be assigned a value when declared
o If not: SyntaxError message
4. Mathematical Assignment Operator:
- Code syntax: w += number; this will add “number” amount to w
- Will be same as other function: -=, *=, /=
- Using this will assign new value for var
5. Increment and decrement for operator:
- Increment operator: ++ this will increase the value of var: +1
- Decrement operator: -- this will decrease the value of var: -1
- It will assign new value for var
- Code syntax: var ++; or var --;
6. String concatenation with variables:
- The + operator can combine two string values even on variables
7. Log string using string interpolation
- Code syntax: .log(`string data ${varName}.`);
- Template literal: it is wrapped by `content`
- Var is wrapped by ${var}
- Benefit: improve readability
8. Typeof operator
- This operator will check the data type of variable value
- Syntax: typeof varName;
o ex: console.log(typeof varName);

CONDITIONALS

1. If keyword:
- Code syntax: if (condition if true) {code block if true}
o (Condition if true): will evaluate with the value and print the output
2. Else statement:
- Code syntax: if (condition if true) {code block if true} else {code block if false}
3. Comparison operator:
- Less than: <
- Greater than: >
- Less than or equal to: <=
- Greater than or equal to: >=
- Equal to: === (compare the value and type of data)
- Not equal to: !==
 A comparison must have:
o 2 values to be compared
o An operator to separate the value and compare them
4. Logical operator:
- Can use logical operators to add more complex logic
- 3 logical operators:
o The “and” op: && - 2 value must be true
o The “or” op: || - either 2 values true
o The “not” op: ! = will negates/reverse the value of Boolean
5. Truthy and falsy
- With non-boolean data type:
o If a variable has value: it is truthy (not falsy). So the condition inside the if syntax is
true
o If a variable has falsy value, which include:
 0
 Empty string “ “
 Null (no value at all)
 Undefined (lack of value)
 NaN (Not a Number)
Then the condition inside the if syntax is falsy
o Ex: let a = 0;
If (a) {console.log(5);} else {console.log(6);} //output: 6
6. Truthy and falsy statement:
- Use to shorten conditionals (called: short-circuit evaluation)
- Ex: let defaultName;
If (username) {defaultName = username;} else {defaultName = “stranger”;}
o The code above can be shorten with truthy and falsy statement:
 let defaultName = username || “stranger”;
o it will check the first value, if true then execute no code after, if false then use the
code after.
7. Tenary operator:
- Simplify if else condition with tenary operator:
- Code syntax: condition ? code block if true : code block if false;
8. Else if statement
- Else if statement will allow more than 2 possible outcomes
- “if” will be followed by “else if” and will be followed by else
- Code syntax:
o If (condition 1) {code block if condition 1 true}
Else if (condition 2) {code block if condition 1 false, condition 2 true}
Else if (condition 3) {code block if condition 2 false, condition 3 true}

Else {code block if all the conditions false}
9. Switch keyword
- Provide an alternate syntax for else if – increase readability and work environment
- Switch syntax:
o Switch (varName) {
Case /value to compare/ : code if true;
break;
case /value to compare/ : code if true;
break;
case /value to compare/ : code if true;
break;

Default : code if all false;
Break;
}
- /value to compare/: just the value, no condition code syntax

JAVASCRIPT: FUNCTION

- Is to group a block of code together and associate it with one task


1. Function declaration
- Is one way to create function
- Binds a function to a name (an identifier)
o Code syntax: function functionName() {function body}
 Function: keyword
 functionName: is an identifier, camel casing, followed by parentheses ()
 function body: block of statements to perform task, enclosed in curly
brackets {} getCompChoice();
 ex: function greetWorld() {console.log(‘hello world’);}
- Hoisting feature: allows a code to access function before they are defined
o Ex: console.log(greetWorld()); output: hello world
function greetWorld() {console.log(‘hello world’);}
2. Calling a function
- A function just declares the code inside, not force it to run
- to call function to run: type the function name followed by ():
o Ex: function greetWorld() {console.log(‘hi’);}
greetWorld(); //output: hi
3. Parameters and Arguments
- All the function above: execute a task without input (information in parentheses)
- Parameters: the placeholders for information pass to the function when it is called
- Parameters are treated as variables in a function
o Ex: function calculateArea(width, height) {console.log(width*height);}
- When calling a function with parameters: specify the values in () with function name
o The values passed to the function when called: an argument
 Arguments can be values or variables
 Ex: calculateArea(10, 6);
 (10, 6) is an argument with value
o The parameters can be used as value in the code – function body
***you can add parameters to function and use that parameters as variables in your
function body (code) and then pass value into the parameters as arguments to execute
code.
o Ex: function sayThanks(name) {
o console.log('Thank you for your purchase ' + name + '! We appreciate your
business.');
o }
o sayThanks("Cole"); //output: Thank you for your purchase cole! We…
4. Default Parameters:
- Allow parameters to have a predetermined value in case there is no argument passed into
the function/if the argument is undefined.
o Ex: function greeting (name = ‘stranger’) {code body}
 If there is a value added to name – name will be displayed
 If there is no value added to name – stranger will be displayed
o (name = ‘stranger’): default parameters
- Return code
- When a function is called: computer will run through the code and evaluate the result. By
default: the resulting value: undefined
- When do we want to use return: when the function generate new value and you want to
pass it back to the caller
- Use return to pass back information from the function call.
o Code syntax: return value; : put the code in the function body
o When return is executed in function code: the execution of function is stopped
there and the code follow will not be executed.
 Ex: function calculate(a, b) {if (a<0 || b<0) {return ‘put a positive number
dumbass’;} return a*b;}
 if a or b<0: return the line and stop there.
5. Helper Function
- The act of returning value of a function inside another function
- Easier to read and debug
6. Function Expressions
- A function with no name: anonymous function
- Can define function name by declaring it in variable
- A function expression: stored in variable to refer it
- To declare a function expression:
o Declare a variable. Common practice: const
o Assign the value an anonymous function by using function keyword and body
o To invoke a function expression: write variable names with arguments passed to
function
7. Arrow function syntax
- A shorter way to write function by using: () =>
o Will remove the need to type the keyword function every time you need to create a
function.
o Shortway: (parameters) => {function body}
8. Concise body arrow function:
- Condensed form of function (concise body)
o With parameters:
 Zero or multiple parameters: (parameters) => {function body}
 One parameter: parameterName => {function body}
o With line block:
 Single-line block will not need curly braces. Without curly braces: whatever
that line evaluate will be returned. And the return keyword will be removed.

Media breakpoints:

https://s3.amazonaws.com/codecademy-content/courses/freelance-1/unit-5/screen-sizes.png

You might also like