Css documentation

Introduction to CSS

The three pillars of writing good CSS

  1. Responsive design
    • Fluid layouts
    • Media queries
    • Responsive images
    • Correct units
    • Desktop first vs mobile first
  2. Maintainable & scalable code
    • Clean
    • Reusable
    • How to organize files
    • How to name classes
    • How to structure HTML
  3. Web performance
    • Less http requests
    • Less code
    • Compress code
    • Use a CSS pre‐processor
    • Less images
    • Compress images

What happens when we load a webpage?

css process

Linking Stylesheets

Link stylesheets with the link element.

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

The order of the Cascade

CSS is declared from the top down, anything declared further down the CSS that clashes will win! If we have multiple CSS files, the order they are linked in the HTML file matters, the first linked CSS will be declared, then the 2nd and so on!

CSS Architecture

  1. Think
    • Think about the layout of the webpage before coding.
  2. Build
    • Build the layout with a consistent structure of naming classes
    • BEM structure as seen below
  3. Architect
    • Create a logical folder acrhitecture for the project
    • The 7‐1 pattern = 7 different folders for partial SASS files & 1 main SASS file to import all other files into a compiled CSS stylesheet, the 7 folders are;
      1. base/ (basic project definitions)
      2. components/ (1 file for each component)
      3. layout/ (define overall layout of project)
      4. pages/ (styles for specific pages)
      5. themes/ (to implement different visual themes)
      6. abstracts/ (code that does not output any css such as variables or mixins)
      7. vendors/ (where all 3rd party css goes)

How to name classes using BEM (Block Element Modifier)

  1. .block
  2. .block__element
  3. .block__element--modifier
.hero
.hero__btn
.hero__btn--round

CSS Selectors

  1. Universal selector, * Select everything in the document. Not very commonly used.
  2. Element selector, button Select all of a certain element for example, all buttons.
  3. Selector list, h1, h2 Select all h1's and h2's.
  4. Decendant selector ol li Select all li's that are nested inside of all ol's. They don't have to be direct decendants to work.
  5. Adjacent selector, h1 + p Selects all the paragraphs that come immediately after a h1 at the same level, not nested.
  6. Direct child selector div > li Selects all li's that are a direct child to a div. (One level down).
  7. Attribute selector input [type="text"] Selects all text inputs. This can select any attribute.
  8. Class attribute selector section.post Selects sections with the class of post.
  9. Other attribute selector a [href^=example] Starts. a [href*=example] Containing. a [href$=example] Ending.

Psuedo Classes

Psuedo classes selects the whole element and starts with a :

  1. :nth‐of‐type(2) Selects just the 2nd element.
  2. :nth‐of‐type(2n) Selects every 2nd element.
  3. :nth‐of‐type(even) Selects every even numbered element.
  4. :nth‐of‐type(odd) Selects every odd numbered element.
  5. :link to design links in the unvisited state (before they are clicked)
  6. :visited to design links in the visited state always use this even if the visited state will look the same as default state
  7. :not(:last‐child) selects everything except the last child, can swap last child out for any other psuedo class.

Psuedo Elements

Psuedo elements select part of an element and starts with ::

  1. ::first‐letter(2) Selects first letter of the element.
  2. ::after to add something after an element, such as adding an arrow to a link on hover. Need to add a content property & display property.

CSS Specificity

The more specific selector wins.

Sepcificity order is as follows;

  1. !important declaration Never use!
  2. Inline Styles Never use!
  3. ID
  4. Class
  5. Element
Specificity Calculator

CSS Inheritance

Elements, if styles not specifically set, will inherit styles from the closest selector such as body or div etc.

Some elements do not inherit styes such as inputs and buttons but you can declare them to inherit styles in stylesheet, for example, color: inherit;

You can set an element to inherit a value by declaring the inherit property.

You can set an element to inherit the initial value by declaring the intial property.

CSS box model

Width & height

width & height properties set the width and height of the content area, but if box-sizing is set to border-box, it sets the width of the border area.

Margin

By default, body has a margin of 8px, common to set body margin to 0 at top of css. This can also be done with normalize.css or reset.css

Inline & Block

Inline

  1. Width and heigh properties are ignored
  2. Horizontal margin and padding respected, vertical is ignored.

Block

  1. Width & height properties are respected
  2. Margin & padding are respected

Inline-Block

Works as an inline element BUT width height margin and padding are all respected.

How to easily center elements inside the box

.class name {
position: absolute;
top: 50%;
left: 50%;
transform: translate( -50%, -50%);
}

  1. We need to set the parent containers postion to position: relative;
  2. The transform property moves the center point from the top left of the box by default to the center of the box using the x & y axis (-50%, -50%)

Measurements Units

Ems

ems are relative to the size of the parent element. For example, if sections font size is 16px, if font size for p inside the sections is set to 2em, that would equal 32px (twice the sections font size).

Rems

rems are relevant to the root HTMLs element font-size. For example, if root font-size is 20px, 1rem = 20px

Change root HTML element font-size by targeting html in CSS.

Tip!

Good practice is to set the root font‐size to 62.5% (10px) and replace all pixel measurements to rems for everything, not just font‐size as this makes it easier for us during responsive design.

It is bad practice to set root font‐size to pixels as people with visual issues cannot change the root size in their browser, so setting percentage of the default browser root font‐size allows users to still change the root font‐size in their browser.

Other CSS elements

Functions

  1. width: calc((100% ‐ 80px) / 2); The calc function can do math using multiple units.

Opacity & rgba

  1. rbga only effects background elements.
  2. opacity effects all elements.

Position property

Sets how the element is positioned in the document.

  1. static How the element is positioned by default, not effected by top left right and bottom properties.
  2. relative How the element is positioned in the document, like static, but we can offset it relative to its default position using top left right and bottom properties.
  3. absolute The element is removed from the document flow and no space is created for the element. If this is not nested inside of a positioned element, it will be positioned relative to the body. To fix the issue of the element being taken out of the document flow, there is no clearfix method like there is with floats, instead we need to declare the height on the parent element (where we delcared the position:relative)
  4. fixed The element is removed from the document flow and no space is created for the element. It will be positioned relative to the body and fixed when scrolling.
  5. sticky Element positioned according to document flow, but once it hits the top of page when scrolling, it will stick there.

CSS Transitions

transition property allows you to transition between states such as default to hover, the following properties accepted are

  1. property name such as background‐color
  2. duration such as 1s
  3. timing function such as ease‐in
  4. delay such as 1s
transition: background‐color 1s ease‐in 1s;

CSS Transform

These properties are used to rotate, move or scale elements.

  1. transform: rotate(); rotates x degrees.
  2. transform: scale(0.5); scales down to half its size.
  3. transform: translateX(200px); moves sideways 200px.

Fonts

When linking fonts, make sure to add the link before the linked CSS in the HTML document.

<link href ="font link" rel="stylesheet"> <link rel="stylesheet" href ="style.css">

Designing Image elements

  1. background‐image: linear‐gradient(to right bottom, rgba(126, 213, 111, 0.8), rgba(40, 180, 131, 0.8)), url(../img/...jpeg); sets background overlay & background image. background overlay should always be stated before the background image.
  2. background‐size: cover; sets if the image should contain, cover etc
  3. background‐position: top; sets the initial position of the image
  4. clip‐path: polygon(0 0, 100% 0, 100% 75vh, 0 100%) clip path creates shape dividers. the polygon property defines the four corners of the images starting from top right going clockwise defining the x and y cordinates.
  5. CSS clip path maker

CSS Flexbox

What is Flexbox?

Flexbox allows us to distribute elements a certain way within the container which makes responsive design easier.

Flexbox is used to create flexible layouts.

Flexbox cheatsheet

Check out this cheatsheet for flexbox

Flexbox properties;

  1. display: flex; sets container to use flexbox.
  2. Main axis - the direction the elements are set to
  3. Cross axis - the spacing between each row or column
  4. flex‐direction allows us to decide main axis direction.
  5. justify‐content determines how elements are distrubited across the main axis.
  6. flex‐wrap determines if elements should wrap onto a new line when overflowing.
  7. align‐items determines how elements are distrubited across the cross axis.
  8. align‐content the space between the rows or columns. Only with flex-wrap on.
  9. align‐self similar to align-content except we add this to a single element to align individual elements instead of every element in the container.
  10. flex‐basis sets height (column) or width (row) of all elements depending on if flex-direction is set to row or column.
  11. flex‐grow controls the amount of space elements take up, if there are extra amounts of space. (Makes elements grow for larger screens, good for responsiveness.)
  12. flex‐shrink controls the rate elements shrink, if there is too little space. (Makes elements shrink for smaller screens, good for responsiveness.)
We can use margin:auto to automatically set a margin to fill the remaining space there is. Very useful when we want to create as much space as possible between elements

Float & clear method

parent‐element::after {
content: "";
clear: both;
display: table;
}

.navigation {
list‐style: none;
float: left;
}

Responsive Designs & Media Queries

  1. media queries also accept orientation (landscape or portrait) as well as min‐width and max‐width
  2. To set a media query for touch devices, you can set media query to hover: none

Responsive images in html

Responsive images relates to which size of an image we should deliver depending on screen size etc. The 3 use cases are;

  1. Resolution switching Decreasing the image resolution for smaller screens
  2. Density switching Decreasing the image resolution for lower resolution screens
  3. Art direction When you want to serve a whole different image for a different sreen size

For normal images, you change in html, for background images, you need to change this in the css.

Example below is density switching using srcset instead of src allows you to add more than 1 image, then adding 1x and 2x after each image file tells the web browser which image is for low res screens and high res screens. 1x is for low res screens and 2x is for high res screens.

<img srcset="img/logo-green-1x.png 1x, img/logo-green-2x.png 2x" src="img/logo-green-2x.png">

It is best to still include the src attribute with the srcset attribute just in case someone is using an old browser that does not understand the new srcset attribute.

Example below is art direction We use the picture element instead of the img element. We then select the default image using the img element. We also set a source element and within that, we specify that at a below screen width size, we display a different image, in the example below, on mobile, we display a different logo.

<picture>
<source srcset="img/logo-green-small-1x.png 1x, img/logo-green-small-2x.png 2x" media="(max-width: 37.5em)">
<img srcset="img/logo-green-1x.png 1x, img/logo-green-2x.png 2x" src="img/logo-green-2x.png">
</picture>

Example below is resolution switching We use the srcset attribute to list the different sized images using a width identifier to let the browser know the width of each image. Then we use the sizes attribute to tell the browser how wide the image should be on different screen sizes as the example below shows, 20% on screens with a max-width of 900px or 30% width on screens with a max-width of 600px. We then also set the default width of 300px for the other screen sizes. Finally we add the src attribute as a backup for old browsers.

The below example sets both resolution switching and density switching. We give the browsers the small and large images with width and screen size values so the browser can deliver the right image for different screen resolutions and screen sizes together.

<img srcset="img/nat-1.jpg 300w, img/nat-1-large.jpg 1000w"
sizes="(max-width: 900px) 20vw, (max-width: 600px) 30vw, 300px">
src="img/nat-1-large.jpg">

Responsive images in css

We use css to change the responsiveness of background images. The example below show how we can use media queries to change the background image if the screen resolution is above 192dpi (apples retina display resolution) and a screen size above 600px in width (larger than mobiles) OR if the screen size is above 2000px wide. In the below example, we use a higher resolution image on screens that are larger than mobile with high resolution.

@media (min-resolution: 192dpi) and @media (min-width: 37.5em),
(min-width: 125em) {
background-image: linear-gradient(to right bottom,
rgba ($color-primary-light, 0.8),
rgba ($color-primary-dark, 0.8)),
url (../img/hero.jpg),
}

Normalize CSS

Different browsers have different padding, margins etc by default, Normalize.css normalizes the default browser settings so your css would be the same on every browser.

Download normalize.css here

How to do a custom CSS reset with the universal selector (*)

*,
*::before,
*::after
{
margin: 0;
padding: 0;
box‐sizing: inherit;
}

html {
font‐size: 62.5%;
}

body {
font‐family: "Lato", san‐serif;
font‐weight: 400;
font‐size: 1.6rem;
line‐height: 1.7;
color: #777;
box‐sizing: border‐box;
}

You add the font properties in the body element so all of the child elements of the body can inherit the font styles.

CSS grid

CSS grid is a new grid layout made in CSS without external frameworks like Bootstrap.

  1. grid‐container any container in the document that I want to add a grid inside. display: grid;
  2. grid‐item any direct descendant of a grid container.
  3. grid‐line any horizontal or vertical lines inside the grid separating the sections. Lines are numbered. Top left point of grid is 1/1.
  4. grid‐cell any cell inside a grid.
  5. grid‐track space between 2 or more lines. (space between rows or columns.)
  6. grid‐area a defined rectangular area inside the grid that covers more than one cell.
  7. grid‐gap Empty space between the grid tracks. (padding around the grid lines.)
  8. justify‐items and align‐items applied to grid container - Align the elements horizontally or vertically.
  9. justify‐self and align‐self applied to element - Align the elements horizontally or vertically.

Css grid cheatsheet

Check out this cheatsheet for css grids

How to use a grid;

  1. Declare a grid on a container using display: grid;
  2. Decide how many columns and rows we want grid‐template‐rows or grid‐template‐columns: 1fr 2fr 1fr; auto will define size based on content inside to fit.
  3. Declare where to place each element grid‐column: 2/4 (from column line 2 to column line 4) grid‐row: 2/3 (from row 2 to row 3).

Tip!

If you want to use 3 equally sized columns or grids, state grid‐template‐columns: repeat(auto‐fill, minmax(300px,1fr)) You can also set a minimum and maximum size of rows or columns with minmax

CSS Grid

You can use grid‐template‐areas and grid‐area to place things in the grid without needing to remember line numbers.

  1. grid‐template‐areas applied to grid container. Uses text-based grid map to apply grid area names to individual cells. Write out each cell of the grid , visually.
  2. grid‐area applied to elements. Specifies what area the element should be placed in.
CSS Grid Area CSS Grid Area

To make responsive design, in media queries, just declare new grid‐template‐rows, grid‐template‐columns and grid‐template‐areas Move the names around in the grid.

Responsive CSS Grid Responsive CSS Grid

Nested Grids

You can create nested grids to create layouts within sections.

Practical approach to CSS Grid

  1. Build an accessbile mobile first website without CSS Grid.
  2. Use mobile first layout as the fallback for all browsers.
  3. Use @support to detect grid support on browser.
  4. At appropriate breakpoints, create layouts with CSS grids and grid-areas.

Use firefox inspect tools to inspect the grid.

Learn more at Grid By Example.

Css animations

@keyframes moveInLeft {
@0% {
opacity: 0;
transform: translatex(-100px);
}

@80% {
transform: translatex(10px);
}

@100% {
opacity: 1;
transform: translate(0);
}

}

.className {
animation: moveInLeft 1s ease‐out;
}

  1. Set keyframes using the @keyframes (name the animation)
  2. Call the animation in an element using the animation property.
  3. If we get weird glitching in the animation, go to the parents container element and input backface‐visibility: hidden;
  4. When using a delay, set animation-fill-mode: backwards; so element is invisible before animating in.

Browser support

For new css properties, we can use the @support query to say, if the css property is supported by the browser, then add these rules. See below for example.

@supports (‐webkit‐backdrop‐filter: blur(10px)) or (backdrop‐filter: blur(10px)) {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}

Custom properties (Css variables)

Css custom properties are variables we can use natively in css.

:root pseudo class is like the html selector with a higher specificity.
:root {
--color-primary: #eb2f64;
}

body {
color: var(--color-primary);
}

Introduction to Bootstrap

Installing Boostrap

2 options, add CDN, or download files and link the css files. Then add the JS script tags to the bottom of the body right before the closing body tag. JS Scripts are needed for some Bootstrap components, see the list here.

Basic Components

  1. .container responsive container with some padding, used on divs.
  2. .container‐fluid responsive containers that span across the full width of the screen.
  3. .container‐m responsive container that goes full width until hitting medium break point then had padding on the sides.

List of sources

  1. Colt Steeles web developer bootcamp 2021
  2. Advanced CSS & Sass course