CSS Essential Training Notes
Referencing CSS
External CSS
HTML 5
HTML 4
@import
- Not recommended because of the potential of slowing down the website.
- Usually used in CSS Pre-processors.
Inline CSS
- Shouldn’t be used widely.
- Overrides defined stylesheets.
Internal CSS
- Inefficient with multiple pages.
- Better than inline CSS.
وصلة للملاحظة الرئيسة
Referencing CSS
External CSS
HTML 5
HTML 4
@import
- Not recommended because of the potential of slowing down the website.
- Usually used in CSS Pre-processors.
Inline CSS
- Shouldn’t be used widely.
- Overrides defined stylesheets.
Internal CSS
- Inefficient with multiple pages.
- Better than inline CSS.
Images and Pixel Density
- Images should be twice of the required size to be shown perfectly on high pixel density displays like Apple Retina.
- Background images should be in between of 1400px and 2000px width.
CSS Syntax
- Selector
- Declaration Block
- Declaration [property: value;]
CSS Values and Units
CSS Values and Units
Numeric
Length datatype
Used to specify sizing with two types of units: absolute and relative.
Absolute
- Fixed unit.
- Not affected by values in relative elements.
- Examples:
- px: Pixel
- cm: Centimeter
- mm: Millimeter
- in: Inch
- pc: Pica (equal to 1/6 of an inch)
- pt: point (equal to 1/72 of an inch)
- width: 1000px;
Relative
- Relational sizing, not fixed.
- Dependent upon values declared in parent and ancestor elements.
- Example: em, rem, vw, vh.
- em: Represents inherited font-size of element.
- rem: Represents the font-size of the root element.
- 1vw = 1% of the width of the viewport.
- 1vh = 1% of the height of the viewport.
- vmin: Equal to the smaller of vw and vh.
- vmax: Equal to the larger of vw and vh.
Unitless Values
- Numbers only:
- Keywords:
Function Values
وصلة للملاحظة الرئيسة
CSS Values and Units
CSS Values and Units
Numeric
Length datatype
Used to specify sizing with two types of units: absolute and relative.
Absolute
- Fixed unit.
- Not affected by values in relative elements.
- Examples:
- px: Pixel
- cm: Centimeter
- mm: Millimeter
- in: Inch
- pc: Pica (equal to 1/6 of an inch)
- pt: point (equal to 1/72 of an inch)
- width: 1000px;
Relative
- Relational sizing, not fixed.
- Dependent upon values declared in parent and ancestor elements.
- Example: em, rem, vw, vh.
- em: Represents inherited font-size of element.
- rem: Represents the font-size of the root element.
- 1vw = 1% of the width of the viewport.
- 1vh = 1% of the height of the viewport.
- vmin: Equal to the smaller of vw and vh.
- vmax: Equal to the larger of vw and vh.
Unitless Values
- Numbers only:
- Keywords:
Function Values
وصلة للملاحظة الرئيسةCSS Selectors
CSS Selectors
Type Selectors
- Matches element name.
h1 {...}
Universal Selectors
- Applies to all elements.
Class Selectors
ID Selectors
- Add the ID attribute to the HTML element
- You define the value
- The value is the selector, starting with a # symbol
- Can only be used once per page.
Descendant Selectors
Creates matching patterns based on the relationship between nested elements
Grouping Selectors
Combining Selectors
Specificity
Specificity determines how browsers decide which CSS rule takes precedence.
- Universal (*)
- Element (p)
- Class / pseudo-class (.example)
- ID (#example)
- Inline Styles
- !important
Specificity Calculator
Advanced Selectors
Child Combinator (>)
Only matches to direct child element
Sibling Combinators (+, ~)
Adjacent Sibling Combinators (+)
General Sibling Combinator (~)
Pseudo-Class Selectors
وصلة للملاحظة الرئيسة
CSS Selectors
CSS Selectors
Type Selectors
- Matches element name.
h1 {...}
Universal Selectors
- Applies to all elements.
Class Selectors
ID Selectors
- Add the ID attribute to the HTML element
- You define the value
- The value is the selector, starting with a # symbol
- Can only be used once per page.
Descendant Selectors
Creates matching patterns based on the relationship between nested elements
Grouping Selectors
Combining Selectors
Specificity
Specificity determines how browsers decide which CSS rule takes precedence.
- Universal (*)
- Element (p)
- Class / pseudo-class (.example)
- ID (#example)
- Inline Styles
- !important
Specificity Calculator
Advanced Selectors
Child Combinator (>)
Only matches to direct child element
Sibling Combinators (+, ~)
Adjacent Sibling Combinators (+)
General Sibling Combinator (~)
Pseudo-Class Selectors
وصلة للملاحظة الرئيسةCSS colors
- Keywords
Resource to get color keywords: http://colours.neilorangepeel.com.
- Hex values (case-sensitive):
#000000
- rgb:
rgb(0, 0, 0)
- rgba:
rgba(0, 0, 0, 1)
with alpha.
- hsl: define a color by hue, saturation and lightness.
hsl(270, 60%, 70%)
.
- Hue is specified as angle, while saturation, and lightness are percentages.
- https://css-tricks.com/examples/HSLaExplorer/
- hsla:
hsla(270, 60%, 70%, 0.7)
with alpha.
Generate color palettes
وصلة للملاحظة الرئيسة
CSS colors
- Keywords
Resource to get color keywords: http://colours.neilorangepeel.com.
- Hex values (case-sensitive):
#000000
- rgb:
rgb(0, 0, 0)
- rgba:
rgba(0, 0, 0, 1)
with alpha. - hsl: define a color by hue, saturation and lightness.
hsl(270, 60%, 70%)
.- Hue is specified as angle, while saturation, and lightness are percentages.
- https://css-tricks.com/examples/HSLaExplorer/
- hsla:
hsla(270, 60%, 70%, 0.7)
with alpha.
Generate color palettes
وصلة للملاحظة الرئيسةCascade
- Order matters, from top to bottom.
!important
Keyword overrides source order and specificity.
Pseudo-classes
- :link :visited :hover :active :focus
Inline block and display
- For inline elements, adding width and height has no effect.
- Adding
display: block
to an inline element will make it display like block elements. - Setting
display: inline
to a block element will give it the characteristics of inline elements. - There is one more value that you’ll probably use more often, which is
inline-block
. This will apply the characteristics of both.- The width and height values will be applied, just like block elements, but the items are displayed side by side, just like inline elements, and they only wrap when there’s no longer any space in the container.
- This is a good example of separating content from style.
- You may want your elements to display on a new line, or on the same line, but instead of picking an HTML element that looks a particular way, choose the most semantic element for the content, and then change the display with CSS.
CSS Box Model
The Box Model
- Content box
- Padding box
- Border box
- Margin box
Example:
- 400 width
- 30 padding-left
- 30 padding-right
- 20 border-left
- 20 border-right
- 500px total width
Element height and width calculation
Final element width = left border + left padding + width + right padding + right border
Final element height = top border + top padding + height + bottom padding + bottom border
Box Properties
- Width
- Height
- Padding
- Margin
- Boarder
Width and Height
The width and height properties change the size of the content box. Inline elements require the display property.
Padding
Padding adds/removes space inside of the element but around the content box.
Margin
Margin adds/removes space around the element.
Border
The border property displays a border between the margin and padding.
وصلة للملاحظة الرئيسة
CSS Box Model
The Box Model
- Content box
- Padding box
- Border box
- Margin box
Example:
- 400 width
- 30 padding-left
- 30 padding-right
- 20 border-left
- 20 border-right
- 500px total width
Element height and width calculation
Final element width = left border + left padding + width + right padding + right border
Final element height = top border + top padding + height + bottom padding + bottom border
Box Properties
- Width
- Height
- Padding
- Margin
- Boarder
Width and Height
The width and height properties change the size of the content box. Inline elements require the display property.
Padding
Padding adds/removes space inside of the element but around the content box.
Margin
Margin adds/removes space around the element.
Border
The border property displays a border between the margin and padding.
وصلة للملاحظة الرئيسةCreating a Content Wrapper
Create a container for just the content.
CSS Typography
Categories of Typefaces
- Script: have a hand-lettered look and tend to be harder to read in small sizes, all caps, or long blocks of text.
- Decorative: Since decorative fonts tend to have big personalities, they too are usually reserved for headings and decorative details when used for the web.
- Monospace: each character uses the same amount of horizontal space. Each character is the same width. Often used for displaying code.
- Serif: distinguished by small, decorative lines, usually at the top or at the bottom of the letters.
- Sans-serif: tend to be viewed as traditional and formal. Sans-serif typefaces do not have decorative lines, and are often thought of as contemporary and modern.
Changing the font-family
Generic font-family Names
- serif (serif fonts)
- sans-serif (sans-serif fonts)
- cursive (script or decorative fonts)
- fantasy (decorative fonts)
- monospace (monospace fonts)
Web-safe fonts: http://cssfontstack.com/
Font Weight
- 100 - Thin
- 200 - Extra Light (Ultra Light)
- 300 - Light
- 400 - Normal
- 500 - Medium
- 600 - Semi Bold (Demi Bold)
- 700 - Bold
- 800 - Extra Bold (Ultra Bold)
- 900 - Black (Heavy)
- Normal is equal to 400 and is also the default for body text
- Bold is equal to 700 and is the default for headings
Font Style
Used to add or remove an italic style. There are three values: italic, oblique,
and normal.
Web Fonts
- Downloaded font files
- Included in your project files just like other files (i.e. images)
- Declare and link to font files using
@font-face
URL of the font
Cross-browser Compatibility
Font Size
font-size: px, em, rem
- Different units for specifying the font size
- Relative values are calculated based on the nearest ancestor element
- Absolute values are fixed and not affected by ancestor elements
font-size: px
- Screens are measured in pixels
- Absolute value, great for accuracy
- Use whole numbers, avoid decimals
- Browser default = 16px
font-size: em
- Named after the letter “m”
- Relative unit
- Can use whole numbers or decimal points
- 1em = inherited font-size
font-size: rem
- root em
- Relative unit
- Only relative to the root element (
<html>
)
- Not affected by parent or ancestor elements
Font shorthand
- font-style
- font-size
- font-weight
- font-family
- font-variant
- line-height
Note:
- Must include values for the font-size and font-family
- May optionally include values for font-style, font-variant, font-weight, and line-height
- Order matters! font-style, font-variant, and font-weight must precede font-size
- font-variant = normal or small-caps only
- font-size/line-height
- font-family must be the last value specified
text-decoration
text-align
- The text-align property can be used to align content within a block element
- Add it to the HTML element itself or the parent element
line-height
- The line-height property sets the height of the space between two lines of text
- Closely related to font-size
- Can use different value types (px, %, ems, rems, or unitless)
text-transform
- The text-transform CSS property specifies how to capitalize an element’s text.
- It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized.
وصلة للملاحظة الرئيسة
CSS Typography
Categories of Typefaces
- Script: have a hand-lettered look and tend to be harder to read in small sizes, all caps, or long blocks of text.
- Decorative: Since decorative fonts tend to have big personalities, they too are usually reserved for headings and decorative details when used for the web.
- Monospace: each character uses the same amount of horizontal space. Each character is the same width. Often used for displaying code.
- Serif: distinguished by small, decorative lines, usually at the top or at the bottom of the letters.
- Sans-serif: tend to be viewed as traditional and formal. Sans-serif typefaces do not have decorative lines, and are often thought of as contemporary and modern.
Changing the font-family
Generic font-family Names
- serif (serif fonts)
- sans-serif (sans-serif fonts)
- cursive (script or decorative fonts)
- fantasy (decorative fonts)
- monospace (monospace fonts)
Web-safe fonts: http://cssfontstack.com/
Font Weight
- 100 - Thin
- 200 - Extra Light (Ultra Light)
- 300 - Light
- 400 - Normal
- 500 - Medium
- 600 - Semi Bold (Demi Bold)
- 700 - Bold
- 800 - Extra Bold (Ultra Bold)
- 900 - Black (Heavy)
- Normal is equal to 400 and is also the default for body text
- Bold is equal to 700 and is the default for headings
Font Style
Used to add or remove an italic style. There are three values: italic, oblique, and normal.
Web Fonts
- Downloaded font files
- Included in your project files just like other files (i.e. images)
- Declare and link to font files using
@font-face
URL of the font
Cross-browser Compatibility
Font Size
font-size: px, em, rem
- Different units for specifying the font size
- Relative values are calculated based on the nearest ancestor element
- Absolute values are fixed and not affected by ancestor elements
font-size: px
- Screens are measured in pixels
- Absolute value, great for accuracy
- Use whole numbers, avoid decimals
- Browser default = 16px
font-size: em
- Named after the letter “m”
- Relative unit
- Can use whole numbers or decimal points
- 1em = inherited font-size
font-size: rem
- root em
- Relative unit
- Only relative to the root element (
<html>
) - Not affected by parent or ancestor elements
Font shorthand
- font-style
- font-size
- font-weight
- font-family
- font-variant
- line-height
Note:
- Must include values for the font-size and font-family
- May optionally include values for font-style, font-variant, font-weight, and line-height
- Order matters! font-style, font-variant, and font-weight must precede font-size
- font-variant = normal or small-caps only
- font-size/line-height
- font-family must be the last value specified
text-decoration
text-align
- The text-align property can be used to align content within a block element
- Add it to the HTML element itself or the parent element
line-height
- The line-height property sets the height of the space between two lines of text
- Closely related to font-size
- Can use different value types (px, %, ems, rems, or unitless)
text-transform
- The text-transform CSS property specifies how to capitalize an element’s text.
- It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized.
CSS Layouts Float and Position
CSS Layouts Float and Position
Float
The float property can be used to change the normal document flow by floating elements to the left or right side of its container. And when elements are floated, they are removed from the normal flow
though they remain part of the flow, resulting in the change of the positioning of the surrounding elements.
-
This will place the image to the left side of its container.
-
The text in the following paragraphs will fill the available area and line up right to the edge of the image.
-
We can add some margin in to create a little space between the image and the text.
-
By putting the background color on the paragraphs, it’s now easier to see that while the text is flowing around the image, the boundaries of the element is actually behind the image.
- Floated elements are taken out of the normal flow, so the other elements move up to fill the space as if the floated element was no longer there.
- But the content of those elements will still make room for the floated element and fill up the remaining space around it.
Clearing the Float
- You can clear the float using the
clear
property.
- The values for clear can be
left
or right
to specifically clear a left or right float, but I like to use the third option, both
, which clears left and right floats.
What if there’s no element to apply the clear to?
Option 1: overflow
Overflow is actually used to specify how to display content that doesn’t fit in its container.
Different overflow values can be used to determine how to display the overflow of content.
hidden
clips the overflow of content, this may be used for decorative content, like an image, but isn’t very useful for text since clipped content can’t be accessed.
auto
adds a scroll bar, but only when there is overflowing content.
scroll
will always show a scroll bar on the X and Y axis, even when the content does not flow outside of its container.
Option 2: “clearfix” Hack
CSS snippet added to the parent of floated elements.
- This group of CSS styles need to be added to the parent of the floated elements.
- When adding the class to the HTML, do not include the colon after.
- This is a pseudo-element and is used in conjunction with another selector.
- This fix has been created and maintained by the developer community, and if you’re curious, the history of this fix can be found in this CSS tricks article.
Option 3: display
Not currently supported in all browsers.
- A newer way is in the works to solve the problem, using the display property with a value of flow-root.
- While this provides a solution, it is not currently supported by all modern browsers, and is still in the draft phase.
box-sizing
box-sizing: content-box
- The initial box-sizing value is content-box.
- Width and height values change the size of the content-box.
- But when padding and border styles are added, they increase the size of the elements, adding to the width and height of the content box.
- Margin just adds the space around the element.
box-sizing: border-box
- Using the border-box value instead, we’ll include the padding and border space within the dimensions set with the width and height properties.
- This will make the content-box smaller, but the overall element will maintain the same width and height values without any adjustments.
The Box Model Fix
- This CSS Layouts Float and Position > box-sizing border-box is often referred to as the box model fix.
- To use this fix, add this CSS code snippet to all of your projects.
- More Resources: 1, 2.
Position
The position property can also be used to change the flow of the document. There are 5 different values. Each responsible for a different type of positioning.
static
: not positioned
relative
: relative to current position
absolute
: relative to containing element
fixed
: relative to the viewport
sticky
: relative to containing element and viewport
Position is also used with a combination of the top, right, bottom, and left properties.
Z-Index
- Every time an HTML element is added within the same container, the elements are stacked in layers on the Z axis.
- An element with a higher stack level is rendered in front of the element with the lower stack level.
- Most of the time, it’s hard to see how the elements stack on the Z index, unless they overlap each other.
Default stacking order
- HTML > floated > in-line > positioned.
- We can use the Z index property to change this, but it only works if the element has some type of position applied to it.
وصلة للملاحظة الرئيسة
CSS Layouts Float and Position
CSS Layouts Float and Position
Float
The float property can be used to change the normal document flow by floating elements to the left or right side of its container. And when elements are floated, they are removed from the normal flow though they remain part of the flow, resulting in the change of the positioning of the surrounding elements.
-
This will place the image to the left side of its container.
-
The text in the following paragraphs will fill the available area and line up right to the edge of the image.
-
We can add some margin in to create a little space between the image and the text.
-
By putting the background color on the paragraphs, it’s now easier to see that while the text is flowing around the image, the boundaries of the element is actually behind the image.
- Floated elements are taken out of the normal flow, so the other elements move up to fill the space as if the floated element was no longer there.
- But the content of those elements will still make room for the floated element and fill up the remaining space around it.
Clearing the Float
- You can clear the float using the
clear
property. - The values for clear can be
left
orright
to specifically clear a left or right float, but I like to use the third option,both
, which clears left and right floats.
What if there’s no element to apply the clear to?
Option 1: overflow
Overflow is actually used to specify how to display content that doesn’t fit in its container.
Different overflow values can be used to determine how to display the overflow of content.
hidden
clips the overflow of content, this may be used for decorative content, like an image, but isn’t very useful for text since clipped content can’t be accessed.auto
adds a scroll bar, but only when there is overflowing content.scroll
will always show a scroll bar on the X and Y axis, even when the content does not flow outside of its container.
Option 2: “clearfix” Hack
CSS snippet added to the parent of floated elements.
- This group of CSS styles need to be added to the parent of the floated elements.
- When adding the class to the HTML, do not include the colon after.
- This is a pseudo-element and is used in conjunction with another selector.
- This fix has been created and maintained by the developer community, and if you’re curious, the history of this fix can be found in this CSS tricks article.
Option 3: display
Not currently supported in all browsers.
- A newer way is in the works to solve the problem, using the display property with a value of flow-root.
- While this provides a solution, it is not currently supported by all modern browsers, and is still in the draft phase.
box-sizing
box-sizing: content-box
- The initial box-sizing value is content-box.
- Width and height values change the size of the content-box.
- But when padding and border styles are added, they increase the size of the elements, adding to the width and height of the content box.
- Margin just adds the space around the element.
box-sizing: border-box
- Using the border-box value instead, we’ll include the padding and border space within the dimensions set with the width and height properties.
- This will make the content-box smaller, but the overall element will maintain the same width and height values without any adjustments.
The Box Model Fix
- This CSS Layouts Float and Position > box-sizing border-box is often referred to as the box model fix.
- To use this fix, add this CSS code snippet to all of your projects.
- More Resources: 1, 2.
Position
The position property can also be used to change the flow of the document. There are 5 different values. Each responsible for a different type of positioning.
static
: not positionedrelative
: relative to current positionabsolute
: relative to containing elementfixed
: relative to the viewportsticky
: relative to containing element and viewport
Position is also used with a combination of the top, right, bottom, and left properties.
Z-Index
- Every time an HTML element is added within the same container, the elements are stacked in layers on the Z axis.
- An element with a higher stack level is rendered in front of the element with the lower stack level.
- Most of the time, it’s hard to see how the elements stack on the Z index, unless they overlap each other.
Default stacking order
- HTML > floated > in-line > positioned.
- We can use the Z index property to change this, but it only works if the element has some type of position applied to it.
Checking Browser Support
- Can I use is a great reference for checking browser support.
- Just do a search for any CSS property, and the search results will show you the browser support.
- There is also additional information, such as known issues or any additional resources.
CSS Layouts Flexbox and Grid
CSS Layouts Flexbox and Grid
- Both Flexbox and Grid are new layout modules that can be used to create layouts that are more advanced than previous techniques.
- While they share some similar syntax and some of the same properties, they each have their own specialties.
- With Flexbox, items are aligned on a single axis. It is often described as being one-dimensional. While you can set the main axis to arrange items as rows or columns, Flexbox only deals with one dimension at time.
- Grid layouts are thought of as two-dimensional, because it can arrange items into rows and columns at the same time.
- While both of these methods can be used for layouts, Flexbox is great for space distribution of items within the same axis. Grid is ideal for layouts that require more control with rows and columns.
Flexbox
https://developer.mozilla.org/en-US/docs/Web/CSS/flex
- flex container: the parent element
- flex items: the child elements
flex-direction
- Determines the direction of the main axis
There are four values: row
, row-reverse
, column
and column-reverse
.
flex-flow Shorthand
flex-
Properties
These must be applied to the flex items directly not to the container.
flex-basis
: sets the initial size of the flex-items
flex-grow
: determines how items will expand if there is extra space in the container
flex-shrink
: determines how items will shrink if there isn’t enough space in the container
flex Shorthand
If you wanted the items to be sized differently, then flex must be applied to the individual flex items.
Alignment
- justify-content aligns items on the main axis
- align-items aligns items on the cross axis
Grid
https://www.mozilla.org/en-US/developer/css-grid/
-
Grids are broken down into evenly spaced columns and rows that are used as a guide for laying out page components.
-
Gutters are often included to add consistent spacing between columns.
-
Page components are arranged within the columns.
-
grid container - the parent element.
-
grid items — the child elements within the grid container
-
When using the value of grid, unless specified, the items will span the width of its container.
-
When using the value of grid, the container will be displayed as block-level element and stacked on top of other block element.
-
When using the value of inline-grid, the items will span the width of its content.
-
When using the value of inline-grid, the whole container will display inline next to other inline containers.
-
Grid lines are the horizontal and vertical lines that divide the grid into columns and rows.
- Grid lines are also used to determine the position of the grid items and are referred to by a numerical index, or by custom name.
- When using a numerical index, both the vertical and horizontal grid lines start at one.
- Grid lines can also be referred to by a negative numerical index which allows you to reference the opposite end of the grid.
-
A grid cell refers to a single unit, defined by where the grid row and column intersect.
- The space between two adjacent grid lines is the grid track, which is basically the columns and rows.
-
Grid tracks can optionally be separated by a gutter.
Explicit Grid
- To define a specific number of grid lines and tracks, use
grid-template-columns
and grid-template-rows
. This will create an explicit grid.
The Fraction Unit: Fr
repeat()
- We can also define multiple tracks using another value, the repeat function.
- Instead of writing 1 fr three times, include the number of tracks, three in this example, followed by a comma and the size of the track such as 1 fr within the parentheses.
Adding Gutters with gap
- The original grid layout specification included the grid-gap, grid-row-gap and grid-column-gap properties.
- It has been updated to gap to be used for both grid and Flexbox.
Implicit Grid
- When using a grid layout, grid template rows and grid template columns are used to define a fixed number of tracks to form an explicit grid. But sometimes you may have more grid items than the number of explicit tracks.
- Once an explicit grid is filled or if no explicit grid has been defined, the grid container will generate implicit grid tracks.
- If you don’t know how many items your grid needs to display you can create the whole grid using only an implicit grid, and if you know the minimum amount of grid items you could use an explicit and implicit grid together.
Defining the grid Structure
Positioning grid Items
Grid Lines and grid-column
Alignment
- justify-items defines the default justify-self for all items of the box, giving them all a default way of justifying each box along the appropriate axis.
- align-items aligns items on the Block Axis within their grid area.
- place-items is shorthand property allows you to align items along both the block and inline directions at once (align-items and justify-items properties).
- justify-content aligns items on the inline axis of a grid container.
- align-content sets the distribution of space between and around content items along grid’s block axis.
- place-content is shorthand property allows you to align content along both the block and inline directions at once (align-items and justify-items properties).
Naming the grid columns/rows
grid-template-areas
The grid-template-areas CSS property specifies named grid areas, establishing the cells in the grid and assigning them names.
وصلة للملاحظة الرئيسة
CSS Layouts Flexbox and Grid
CSS Layouts Flexbox and Grid
- Both Flexbox and Grid are new layout modules that can be used to create layouts that are more advanced than previous techniques.
- While they share some similar syntax and some of the same properties, they each have their own specialties.
- With Flexbox, items are aligned on a single axis. It is often described as being one-dimensional. While you can set the main axis to arrange items as rows or columns, Flexbox only deals with one dimension at time.
- Grid layouts are thought of as two-dimensional, because it can arrange items into rows and columns at the same time.
- While both of these methods can be used for layouts, Flexbox is great for space distribution of items within the same axis. Grid is ideal for layouts that require more control with rows and columns.
Flexbox
https://developer.mozilla.org/en-US/docs/Web/CSS/flex
- flex container: the parent element
- flex items: the child elements
flex-direction
- Determines the direction of the main axis
There are four values: row
, row-reverse
, column
and column-reverse
.
flex-flow Shorthand
flex-
Properties
These must be applied to the flex items directly not to the container.
flex-basis
: sets the initial size of the flex-itemsflex-grow
: determines how items will expand if there is extra space in the containerflex-shrink
: determines how items will shrink if there isn’t enough space in the container
flex Shorthand
If you wanted the items to be sized differently, then flex must be applied to the individual flex items.
Alignment
- justify-content aligns items on the main axis
- align-items aligns items on the cross axis
Grid
https://www.mozilla.org/en-US/developer/css-grid/
-
Grids are broken down into evenly spaced columns and rows that are used as a guide for laying out page components.
-
Gutters are often included to add consistent spacing between columns.
-
Page components are arranged within the columns.
-
grid container - the parent element.
-
grid items — the child elements within the grid container
-
When using the value of grid, unless specified, the items will span the width of its container.
-
When using the value of grid, the container will be displayed as block-level element and stacked on top of other block element.
-
When using the value of inline-grid, the items will span the width of its content.
-
When using the value of inline-grid, the whole container will display inline next to other inline containers.
-
Grid lines are the horizontal and vertical lines that divide the grid into columns and rows.
- Grid lines are also used to determine the position of the grid items and are referred to by a numerical index, or by custom name.
- When using a numerical index, both the vertical and horizontal grid lines start at one.
- Grid lines can also be referred to by a negative numerical index which allows you to reference the opposite end of the grid.
-
A grid cell refers to a single unit, defined by where the grid row and column intersect.
- The space between two adjacent grid lines is the grid track, which is basically the columns and rows.
-
Grid tracks can optionally be separated by a gutter.
Explicit Grid
- To define a specific number of grid lines and tracks, use
grid-template-columns
andgrid-template-rows
. This will create an explicit grid.
The Fraction Unit: Fr
repeat()
- We can also define multiple tracks using another value, the repeat function.
- Instead of writing 1 fr three times, include the number of tracks, three in this example, followed by a comma and the size of the track such as 1 fr within the parentheses.
Adding Gutters with gap
- The original grid layout specification included the grid-gap, grid-row-gap and grid-column-gap properties.
- It has been updated to gap to be used for both grid and Flexbox.
Implicit Grid
- When using a grid layout, grid template rows and grid template columns are used to define a fixed number of tracks to form an explicit grid. But sometimes you may have more grid items than the number of explicit tracks.
- Once an explicit grid is filled or if no explicit grid has been defined, the grid container will generate implicit grid tracks.
- If you don’t know how many items your grid needs to display you can create the whole grid using only an implicit grid, and if you know the minimum amount of grid items you could use an explicit and implicit grid together.
Defining the grid Structure
Positioning grid Items
Grid Lines and grid-column
Alignment
- justify-items defines the default justify-self for all items of the box, giving them all a default way of justifying each box along the appropriate axis.
- align-items aligns items on the Block Axis within their grid area.
- place-items is shorthand property allows you to align items along both the block and inline directions at once (align-items and justify-items properties).
- justify-content aligns items on the inline axis of a grid container.
- align-content sets the distribution of space between and around content items along grid’s block axis.
- place-content is shorthand property allows you to align content along both the block and inline directions at once (align-items and justify-items properties).
Naming the grid columns/rows
grid-template-areas
The grid-template-areas CSS property specifies named grid areas, establishing the cells in the grid and assigning them names.
وصلة للملاحظة الرئيسةCSS Responsive Web Design
https://alistapart.com/article/responsive-web-design/
- Fluid layout
- Flexible images
- Media queries
Fluid Layouts
- Instead of fixed-width pixels, we’ll update our project to percentage-based values and use min and max width properties to create a flexible foundation.
- When the viewport is wider than the max width, the content wrap maxes out at the defined value, 800 pixels in this example.
- When the viewport is smaller than the max width value, it will apply the width value.
Flexible Images
There’re two ways to add images to a webpage.
- Images that are part of the content should be added with HTML
- Images that are presentational should be added with CSS
-
We’ve used the Shorthand Syntax background
to set the color, but the Longhand Properties actually background-color
.
-
background-image
is used to with a URL function value with the path to the image added within the parentheses.
-
If the image file is smaller than the area you applied it to, it will automatically repeat the image on the x and y-axis to fit the entire area. To keep the image from repeating, use the background-eepeat
Property set to no-repeat
.
-
By default, the background image is aligned to the top left of the container. background-position
can be used to define the position of the image relative to its container.
- One value represents the positioning from the left of the container.
- Any length value can be used.
- The top value defaults to auto, which will aligned the image vertically.
- Use a second value to specify the position from the top.
- There are also five keywords: top, bottom, left, right, and center.
-
To get the image to cover the entire area without repeating, background-size
can be used to set the width and the height.
- The first value is applied to the width.
- Use a second value to change the height of the image.
-
A 100% will make it stretch all the way across and is relative to its container.
-
Another option is to use the keyword cover
. To maintain the aspect ratio, the part of the image that doesn’t fit into the container will be clipped.
- This is not a perfect solution, especially if an important part of the image is not shown. We can use the Background Position Property to move a specific part of the image within the viewable part of the container.
background
Shorthand
background-size
may only be included after position, separated with the ’/’ character
- background-size may be declared independently
More Info: https://developer.mozilla.org/en-US/docs/Web/CSS/background
Media Queries
-
Media queries make it possible to modify the CSS depending on specific conditions, defined with a media type and a media feature.
-
Media queries are added to the CSS file using the @media rule.
-
In this example, this query translates to: when the browser view port is smaller than 1000 pixels, apply this block of CSS. If this condition is not met, the CSS is ignored.
Media Types
Declaring the media type is optional, so if you don’t include it, it will default to all.
- all: matches to all devices
- print: matches to printers and print-related displays
- speech: matches to screen reading devices that “read out” a page
- screen: matches all devices that aren’t categorized as print or speech
Media Features
- Media features are used to test a specific feature of the device
- Use keyword “and” to combine media features with media types
- There are more logical operators, such as “not” or “only.”
- There are also quite a few media features: width, height, aspect ratio, and more.
More info: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Where do we include the media query?
- It’s convention to either add all the media queries at the bottom of the CSS file.
- Or add the media query beneath the related CSS style.
- This way of adding media queries is a little more commonly used when writing CSS with preprocessors such as Sass or Less.
-
You can also write all your media queries in a separate style sheet, and then load them into the main CSS file.
- Use @import to load the stylesheet into the main CSS file.
- Use
<link>
to load the stylesheet into the HTML file.
Breakpoints
- 320px: Mobile portrait
- 480px: Mobile landscape
- 600px: Small tablet
- 768px: Tablet portrait
- 940-1024px: Tablet landscape
- 1280px and greater: Desktop, laptop
Width Media Feature
- When using the Width Media Feature, the media query test applies to the width of the browser viewport.
- Width is classified as a range feature, meaning that we can also use a min or max prefix to specify a minimum or maximum value.
- Using the min or max value works better than just width because it specifies a range such as larger than or smaller than.
- If we use width alone, then it only applies if the viewport is exactly equal to the defined value.
min-
and max-width
Breakpoints
- Sometimes when you’re using both min and max-width values, you may end up targeting the same resolution.
- A simple solution for this would be just to make one of the values one pixel smaller or bigger.
Designing for different screens
There are two schools of thought when designing for different screens.
- One is Desktop First, meaning you design and write your CSS for bigger screens first.
- Media queries are then used to make changes for smaller screens.
- This approach usually uses max-width media queries.
- A Mobile First approach is the opposite.
- The designs in CSS cater to smaller sizes first.
- Media queries are then used to make changes for bigger screens.
- This approach usually uses min-width media queries.
You can also combine both min and max to create a range.
viewport meta tag
- There’s one more thing you need to make sure is included before we finally get to adding media queries. The viewport meta tag.
- This is added to the head section of the HTML document, and is used to control the viewport’s size and scale and optimize the document for mobile viewing.
- The values in the content attribute set the page to render the same width as the device.
- Also, setting the initial scale to one, just means that the page won’t appear zoomed in or out on page load.
- More: https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
وصلة للملاحظة الرئيسة
CSS Responsive Web Design
https://alistapart.com/article/responsive-web-design/
- Fluid layout
- Flexible images
- Media queries
Fluid Layouts
- Instead of fixed-width pixels, we’ll update our project to percentage-based values and use min and max width properties to create a flexible foundation.
- When the viewport is wider than the max width, the content wrap maxes out at the defined value, 800 pixels in this example.
- When the viewport is smaller than the max width value, it will apply the width value.
Flexible Images
There’re two ways to add images to a webpage.
- Images that are part of the content should be added with HTML
- Images that are presentational should be added with CSS
-
We’ve used the Shorthand Syntax
background
to set the color, but the Longhand Properties actuallybackground-color
. -
background-image
is used to with a URL function value with the path to the image added within the parentheses. -
If the image file is smaller than the area you applied it to, it will automatically repeat the image on the x and y-axis to fit the entire area. To keep the image from repeating, use the
background-eepeat
Property set tono-repeat
. -
By default, the background image is aligned to the top left of the container.
background-position
can be used to define the position of the image relative to its container.- One value represents the positioning from the left of the container.
- Any length value can be used.
- The top value defaults to auto, which will aligned the image vertically.
- Use a second value to specify the position from the top.
- There are also five keywords: top, bottom, left, right, and center.
-
To get the image to cover the entire area without repeating,
background-size
can be used to set the width and the height.- The first value is applied to the width.
- Use a second value to change the height of the image.
-
A 100% will make it stretch all the way across and is relative to its container.
-
Another option is to use the keyword
cover
. To maintain the aspect ratio, the part of the image that doesn’t fit into the container will be clipped.- This is not a perfect solution, especially if an important part of the image is not shown. We can use the Background Position Property to move a specific part of the image within the viewable part of the container.
background
Shorthand
background-size
may only be included after position, separated with the ’/’ character
- background-size may be declared independently
More Info: https://developer.mozilla.org/en-US/docs/Web/CSS/background
Media Queries
-
Media queries make it possible to modify the CSS depending on specific conditions, defined with a media type and a media feature.
-
Media queries are added to the CSS file using the @media rule.
-
In this example, this query translates to: when the browser view port is smaller than 1000 pixels, apply this block of CSS. If this condition is not met, the CSS is ignored.
Media Types
Declaring the media type is optional, so if you don’t include it, it will default to all.
- all: matches to all devices
- print: matches to printers and print-related displays
- speech: matches to screen reading devices that “read out” a page
- screen: matches all devices that aren’t categorized as print or speech
Media Features
- Media features are used to test a specific feature of the device
- Use keyword “and” to combine media features with media types
- There are more logical operators, such as “not” or “only.”
- There are also quite a few media features: width, height, aspect ratio, and more.
More info: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Where do we include the media query?
- It’s convention to either add all the media queries at the bottom of the CSS file.
- Or add the media query beneath the related CSS style.
- This way of adding media queries is a little more commonly used when writing CSS with preprocessors such as Sass or Less.
-
You can also write all your media queries in a separate style sheet, and then load them into the main CSS file.
- Use @import to load the stylesheet into the main CSS file.
- Use
<link>
to load the stylesheet into the HTML file.
Breakpoints
- 320px: Mobile portrait
- 480px: Mobile landscape
- 600px: Small tablet
- 768px: Tablet portrait
- 940-1024px: Tablet landscape
- 1280px and greater: Desktop, laptop
Width Media Feature
- When using the Width Media Feature, the media query test applies to the width of the browser viewport.
- Width is classified as a range feature, meaning that we can also use a min or max prefix to specify a minimum or maximum value.
- Using the min or max value works better than just width because it specifies a range such as larger than or smaller than.
- If we use width alone, then it only applies if the viewport is exactly equal to the defined value.
min-
and max-width
Breakpoints
- Sometimes when you’re using both min and max-width values, you may end up targeting the same resolution.
- A simple solution for this would be just to make one of the values one pixel smaller or bigger.
Designing for different screens
There are two schools of thought when designing for different screens.
- One is Desktop First, meaning you design and write your CSS for bigger screens first.
- Media queries are then used to make changes for smaller screens.
- This approach usually uses max-width media queries.
- A Mobile First approach is the opposite.
- The designs in CSS cater to smaller sizes first.
- Media queries are then used to make changes for bigger screens.
- This approach usually uses min-width media queries.
You can also combine both min and max to create a range.
viewport meta tag
- There’s one more thing you need to make sure is included before we finally get to adding media queries. The viewport meta tag.
- This is added to the head section of the HTML document, and is used to control the viewport’s size and scale and optimize the document for mobile viewing.
- The values in the content attribute set the page to render the same width as the device.
- Also, setting the initial scale to one, just means that the page won’t appear zoomed in or out on page load.
- More: https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag