Show Menu
Cheatography

HTML+CSS Cheat Sheet (DRAFT) by

This is for anybody who wants it and it displays basic HTML notions.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Elements

<di­v>
<se­cti­on>
<a>
<link rel="" href="">

Positi­oning elements

position attribute
position: static
The default, their normal position. (inline, block...)
position: relative
Position relative to itself. It only affects selected element so it will not affect others.
 
Can be used alongside 'left', 'right­','­top­','­bottom' to move in the opposite position
 
Can be used alongside 'z-ind­ex'­,'x­-index' to move alongside the x or y axis, 0 by default, like 3D maps.
position: absolute
Position relative to its container, so its movement will affect other elements because it stops belonging to the same plane as the others, like a layer. The contai­ner's position must be relative.
position: fixed
It always stays the same place, because its position is relative to the viewport.

Floating elements

Block elements take up the whole block, line elements take up the line. We can line elements up with properties like float.
float: (left/­right)
The element with this property will float on that direction inside the container, and their siblings will float around it.
clear: (left/­rig­ht/­both)
Stops the element from floating around the element who has the float property on.
.conta­ine­r::­after{ content: ''; display: block, clear: both }
Containers don't detect floating elements, so if other content is removed they will collapse and the floating element will overflow.
overflow: auto;
.class­-na­me:­:be­fore{ content: url()}
To position elements in the page, like stickers or badges
 
If you're going to make its position absolute, make the parent's position relative

FlexBox (Flexible box layout)

A layout method for laying out elements in one dimension, row or column
display: flex;
Activates this layout method. Used in container element.
flex-d­ire­ction: row;
The default, lines elements out horizo­ntally.
flex-d­ire­ction: column;
Vertic­ally.
flex-d­ire­ction: column­-re­verse;;
flex-d­ire­ction: row-re­verse;
Aligning items
row
Align across main axis (horiz­ontal)
justif­y-c­ontent (flex-­sta­rt(­def­aul­t)/­fle­x-e­nd/­cen­ter­/sp­ace­-ev­enl­y/s­pac­e-a­rou­nd/­spa­ce-­bet­ween)
main axis
column
Align across cross axis (vertical)
align-­items (flex-­sta­rt(­def­aul­t)/­fle­x-e­nd/­cen­ter/)
cross axis
Flex containers want to fit the same amount of children in the same line.
flex-w­rap­(no­-wr­ap(­def­aul­t)/­wrap)
when there's no more container width available, items make themselves smaller to fit in the same line/items jump to the next line.
align-­content ()
align-­sel­f(f­lex­-st­art­/fl­ex-end)
Use on the child element, overrides other container porperties directed to child

Grid

Grids are useful for distri­buting elements in rows and columns at the same time.
Under Inspect, if we click the tag 'grid' next to the element we can visualize the grid's size and distri­bution
Display: grid
Define a grid in the container
grid-t­emp­lat­e-c­olumns: 100px 100px;
Define 2 columns
grid-t­emp­lat­e-rows: 100px 100px 100px;
Define 3 rows
grid-t­emp­lat­e-rows: repeat(3, 100px);
grid-t­emp­late: repeat(3, 100px) / repeat(2, 100px)
Define 2 columns and 3 rows
Center grids and its' content (default is stretch)
justif­y-i­tems: center; align-­items: center; justif­y-c­ontent: center; align-­con­tent: center;
Stretch to fit size
(DEFAULT)
grid-t­emp­late: repeat(3, 100px) / 30% 70%
Define two columns, each occupying x% of the available space
grid-t­emp­late: repeat 100px auto 100px/ 30fr 70fr
Define two columns, each occupying the respective fraction of the available space. The row in the middle will decrease and increase with the screen, top and bottom will stay fixed
Defining gaps
row-gap
column-gap
gap
Placing items
grid-row
(n)moves item to n row, (n/x) item starts from n and finishes in x row (see grid tag)
grid-c­olu­mn(n, n/x)
(n) moves item to n column, (n/x) item starts from n and finishes in x line (see grid tag)
grid-area (n/x/y/z)
The first two n represent the start (row,c­olumn), the last two the item numbers (start, end)
grid-t­emp­lat­e-a­rea­s("" "­")
Set up the grid to host a grid template, the properties are written like classes: two headers: "­header header­", The second quotes are used for rows:"row1 row2"
grid-area
Reference the properties mentioned in last one
To auto-fill the fraction for the column with as many inputs as given: grid-t­emp­lat­e-c­olumns: repeat­(au­to-fit, minmax­(100px, 1fr));

Animat­ions: 2d transf­orm­ations

 
The transform property is used for these animat­ions. They can be used on pseudo­-pr­ope­rties like :hover or alone.
transform: rotate­(-1­5deg);
transform: scale(­1.5);
transform: skew(1­5deg);
transform: transl­ate­(10px, 50px);
Moves an element to a specific position. Better than absolute positi­oning.
To use more than one transf­orm­ation:
transform: rotate­(30deg) scale(2);
The order in which they're called matters, it will rotate first and scale second.

Animat­ions: 3D transf­orm­ations

The difference with 2d animations is that not just vertical and horizontal axis are included, but X and Y, which are able to position the element 'closer' or 'further away'.. To use 3d in animations transf­orm() is included. The rotation origin is the center of the element in a X or Y axis point of view, like a matrix.
 
transform: perspe­cti­ve(­200px) rotate­Y(5­0deg);
The position where its transf­ormed from can be changed from the center to others with transf­orm­-or­igin, and it uses X and Y.
0 0 on transf­orm­-origin sets the center on the top left corner.
transf­orm­-or­igin: 0 0;
This transf­orm­ation starts from the left and the middle
transf­orm­-or­igin: 0 50%;
If many elements are to share an animation, they have to use the same class for transf­orm(). This is easily done setting a container class.

Animat­ions: Transi­tions

//For animations to appear smooth between one step and the next we can use transitions.

Properties to use: linear, ease-in (starts slow, continues as expected), ease-out (starts as expected, ends slow), cubic-bezier(.29,.13,.29,.8) (you determine the speed of the transform)

.box-2 {
    width: 100px;
    height: 100px;
    background: red;
    margin: 3rem;
    transition: transform 0.5s ease-in-out 0.3, background 1s;
}

.box:hover {
    transform: rotate(-15deg);
    transform: scale(1.5);
    transform: skew(15deg);
    transform: translate(10px, 50px);
    transform: rotate(30deg) scale(2);
    background: brown;
}
cubic-­bez­ier.com lets you manually pick the kind of bezier curve animation to use with its inputs

The next numeric value input is for animation delay, it takes 0.3 seconds to start after hovering it.

You can use more properties than transform to animate, you can also use background which will shift the background color

Animations pt. II

Animations can be more intricate than what we've seen so far.
@keyframes animat­ion­Name{}
We specify what happens in each keyframe. This property is divided in other small proper­ties.
.. 0% { transform: scale(1);} ...
.. 50% { transform: scale(5);} ...
To call this animation, in the element we want using it, we declare:
.box3{ animat­ion­-name: animat­ion­Name; animat­ion­-du­ration: 5s;}
Other properties include
animat­ion­-delay: 1s;
animat­ion­-it­era­tio­n-c­ount: infinite;
The amount of times you want to repeat this animation. Use 0-9 and infinite for a loop.
animat­ion­-ti­min­g-f­unc­tion: ease-in;
The timing functions to use, like in transform, you can make it start slow and continue at normal speed (ease-in), etc.
animat­ion­-di­rec­tion: alternate;
Determines if you want to start the animation from start to end, from end to start or to alternate from start to end and from end to start.

Reusable animations

<div class=­"­ani­mat­ion­-po­p"
animat­e.style lets you use pre-made animations

Best practices

- Follow a naming conven­tion: kebab case(.k­eb­ab-­case), camel case (camel­Case), pascal case (Pasca­lCase), underscore (under­_sc­ore).
- Create logical sections on your styles­heet: big projects will need different styles­heets for each logical case which are then combined in a main one. Even in one stylesheet try to differ­entiate different concerns, such as basic styles, typogr­aphy, forms, navBar, etc.
- Avoid over-s­pecific selectors: avoid direct children, element names, repeating the same name class over the document (specify, such as 'nav-i­tem').
- Avoid !impor­tant.
- Sort CSS proper­ties: to automa­tically sort CSS properties type >sort in the command line up top.
- Take advantage of style inheri­tance: to get the same font style in a link and a list, for example, give the font to the parent element.
- Extract repetitive patterns.
- Avoid repetitive values in your code.
* Select­ion> Add cursor below will show you how to edit multiple lines at the same time.
* To address children of a same class use .mom .kid{}
* To automa­ticam

Variables or custom properties

:root
This is a pseudo­-class selector. We can use it to define custom properties or global variables.
{ --colo­r-p­rimary: red; }
This is a variable set on :root.
.mainText { backgr­ound: var(--­col­or-­pri­mary);}
This is a variable applied inside of a selector.

Object Oriented CSS

- Separate the content from the container
Make a style just for the button class so it applies to all buttons, not just the ones inside .conta­iner:
.container .btn {}
.btn{}
- Separate structure from skin
Make classes that purely define the structure or logic (a button having rounded edges, a specific font, no border) and clases for 'skin' (such as a button's color, size...)

BEM: Block Element Modifier

This coding practi­ce/­con­vention sees website's grouped elements as 'blocks' of content that form an 'all'. A block can contain elements or other blocks.
In this conven­tion, classes act as separa­tors, and are named likeso: card, card__­header, btn (it's used indivi­dually of the card and will be adressed as the card's child), body
The 'modifier' bit refers to bits of website's elements that have the same use but look different, like a subscr­iption list where Premium membership is a different color. In this case, the class naming convention will be: card--­pre­mium.
'__' is used to differ­entiate a block from an element and '--' to differ­entiate a block from a modifier.

Setting up a project

Create and open the project folder with VSC.
Create the file index.html with boiler­plate code. (! + Shift)
Make a css folder and create a styles.css file and a normal­ize.css file (Google the last one, it's for compat­ibi­lity).
Link both styles­heets in <he­ad>
In the Source Control pannel, click 'Initi­alize Reposi­tory'. Add all new files and click the 'Commit' or 'Okay' button.

Color palettes

Typically composed of primary, seocndary and accent colors.
It's recomm­ended to classify colors in variables
:root { --colo­r-p­rimary: #000; --colo­r-a­ccent: #222}

Typography

Use the designer's photoshop mockup to select font types and sizes.
To decrease download price, select the specific styles you need with care. (Regular 300, Bold 500... etc).
Instead of PX its prefer­rable that you use REM
font-size: 62,5%; means that default font size is not 16px anymore but 10px, so 1rem will be 10px
Measure the distance between p and h, for rule of assici­ation, and adjust depoending on perceived space and actual space. Remember that when two margins meet, they collapse, meaning they become one.

Project - Links

 

Sprites

SVG files can be edited with CSS.
To combine and use many SVG items, we can use a sprite. A sprite can be generated using https:­//s­vgs­pri­t.es/
To reference the svgs inside the sprite, use:
<svg class=­"­ico­n"> <use xlink:­hre­f="../i­mag­es/­spr­ite.sv­g#w­ord­pre­ss">­</u­se> </s­vg>
To style them use CSS as usual.

Shadows

box-sh­adow: x y z w;
x: horizo­ntal, y: vertical; z: blurri­ness; w: shadow length;

Blocks

Navigation bars
 

The BOX model

The numbers indicate the amount of space reserved for them. In here, content takes up 519pxx91px and there's a top and bottom margin of 16.

The BOX model

This model refers to an element being put inside an invisible box when the DOM document is rendered.
At the core of the box there's the content area where content is displayed.
Box: <p>
Content area: text blah blah
Outside of the content area we have the padding area used to add some space outside of the content area.
Next we have the border area
On top we have the margin area used to create some space between elements, other boxes.
For CSS, the rules are applied with trouble: top, right, bottom, left.
p { padding: 10px 20px 10 px 20px;}
10px 20px
10px 20px 10px
10px for top and bottom, 20 for right and left
If two elements are next to each others their margins collpase, meaning they're combined and they share the same space.

Sizing elements

width, height properties
they size the content area up or down
padding
it sizes up or down the padding
margin
it sizes up or down the margin
border (style, size color)
can size up the box if size is changed
box-si­zing: conten­t-box;
all box pieces add up to the size to the box but margin, which separates elements from others
box-si­zing: border­-box;
Adds everything up from the border so the total is 100px
 
We can use the universal () selector to apply the border-box property on all elements. For pseudo­-el­ements: ((::before, *::aft­er...))
width and height only apply to block level elements, which take up the whole horizontal space. If you add another element after a first one, it will start on the next block of space
Inline elements don't respect width and height
Block elements use display: block; by default, inline display: inline;
display: inline­-block
They can use width, height and not start in a new line

Overflow

When an element has a fixed size, content exceedind the designated space might happen. This is overflow.
There are CSS properties to control this:
overflow: hidden;
hides the exceeding elements
overflow: scroll;
Gives you the option to scroll down to see the overflow content
overflow: auto;
The overflow property actually has axis x and y, so you can combine these
overflow: hidden scroll;
Hide the content on x axis and scroll on y

Overfl­owing content

Measur­ement units

px
pixel size, absolute: it stays the same size regardless of device or screen size.
%
size relative to the size of the container, it takes up x % of the parent element's size. Browser's default is 100% width and 0% height (extends with content)
vw
size relative to viewport, it takes up the whole horitontal width space, regardless of content
vh
size relative to viewport, it takes up the whole vertical height space, regardless of content
em
size relative to the font size of parent (10em -> 10 times)
rem
size relative to the font size of the root element (16px by default). If we set html's font-size to 65,5% it will be 10px.

Images

There's two kind of images: raster, made up by pixels, and vectors made up by mathem­atical vectors. Raster images usually come from cameras or scanners. The more amount of pixels the bigger image file size, if smaller because they have less pixels, the blurrier they look. Vectors are softwa­re-made and look sharp at any size.
To check image compat­ibi­lity, you can use canius­e.com
Another two types: content images and background images.
background property
It's used to set a background color OR image, to use as image: backgr­ound: url(/r­oute)
backgr­oun­d-r­epeat:
no repeat / repeat-x (alongside horizontal axis) / repeat-y
backgr­oun­d-p­osition
num num (right­,down); By default backgr­ounds start from top left of the conmtainer element, we can move them around with this property
backgr­oun­d-size
(right­,down) or 100vh - remember that default height of elements is 0 before setting this!
backgr­oun­d-a­tta­chment
fixed (backg­round will not move even if you scroll and content does move)
To check downloaded images by browser: Inspect, Network, Img. Many images will cause too many requests.
CSS Sprites can help lower the workload of user requests. https:­//c­sss­pri­tes­too­l.com/ -> We can download, add the new image, copy the css rules and use only one image, likeso: span class=­"­bg-­dis­hes­" (class prefix, image name for each). It's useful for small icons, not for all pictures because it will create a huge image file.
Data URIs encode image files. They are protocoled in "­dat­a:(...)­" form, which goes inside the 'src' tag. It loads faster but is heavier (on desktop).
Clipping creates a path around an image and displays it in different shapes
clip-path: polygon(x z, 100% 0, etc)
x,z offsets: top-left, top-right, bottom­-right, bottom­-left
Filters change the look of image elements, can be combined with pseudo­-se­lectors for a clean look
filter: graysc­ale­(70­%)/­blu­r(10px)
Supporting high-d­ensity screens (high res): Provide two files of the same image, one with x amount of pixels and another with twice the amount. Physical resolution and logical resolution are different, CSS uses logical. To use images with different DPR, we can export the same image into smaller sizes, depending on the sizes we want to use. Generally export at 7. Instead of using 'src' you can use 'scrset' for multiple sources.
srcset­="im­age­s/m­eal.jpg 1x, images­/me­al@­2x.jpg 2x"
Support multiple sources of the same image in different DPRs
Resolution switching to fetch one image or the other depending on width
srcset­="im­age­s/m­eal.jpg 400w , images­/me­al@­2x.jpg 800w" sizes=­" (max-w­idth: 500px) 100vw, (max-w­idth: 500px) 50%"
respon­siv­ebr­eak­poi­nts.com is useful to set different image resolu­tions for each breakpoint
To use lighter images, we can convert them to webp format. I might have to use 'picture' for better support with type as webp and jpg.
To utilize art direction, for which shows different images on different display sizes. With this, different sources will be picked depending on each query
<pi­ctu­re>­<source media=­"­(ma­x-w­idth: 500px)­" src=""
Icons
fontaw­eso­me.com gives you free icons to use on your website
<i class=­"­fa-­solid fa-leaf fa-rot­ate­-by­" style=­"­color: #4b511f; --fa-r­ota­te-­angle: 2deg; fa-2x"">­</i>
 
<span class=­"­ico­n"><i class=­"­fa-­solid fa-lea­f"><­/i>­</s­pan>

Hiding elements

display: none;
It hides the element as if it was never there.
visibi­lity: hidden;
Allocates space for hidden el

Media queries

Used to create responsive websites because they adapt to the device using it, not the other way around.
On Chrome: View > Developer > Chrome DevTools > Toggle device ToolBar you can check the viewport size and how it looks in different screens
Breakpoint
When after changing sizes the screen looks bad. Use this as a basis, not popular device models.
@media
The type of media it will adress, used in breakp­oints
@media screen
For web browsers
@media print
For printers. Useful to set font sizes to pt and cm for sizing.
@media screen and()
Create a condition
@media screen and(mi­n-w­idth: 600px)
If the condition is applied (minimum size of screen is 600px) the rules will apply, otherwise they won't. Classes can be referenced to inside.

Pseudo­-class selectors

.box:n­th-­of-­type(x)
Style the x occurrence with this class ('box')

Font types

Typography

There's 3 fonts, serif, sans-serif and monospace
Styling fonts
font-f­amily
 
Determines the font used by the element.
Font stacks
font-f­amily: Arial, Helvetica, sans-s­erif;
Multiple fonts, if the first font is not available, the computer looks for the next in line. The third is a generic font, and will be one of the three: serif, sans-serif or monospace.
font-w­eight
100-900, bold(7­00)­,bo­lde­r,l­igh­ter­,no­rma­l(400)
Determines the bolness of the font.
font-style
normal­,it­ali­c,bold
font-size
px,em,rem,
Determines the size of the font.
System font stack
Each computer will interpret the font differ­ently depending on OS or version. To make sure the website is readable for the user, this approach is recomm­ended.
font-f­amily: (apple­-sy­stem)
Sizing fonts
Pixels (px) will look different on different OS, browsers ... it's better to use relative units. It's 16px by default. 1 rem is equal to the default font (16px * 1rem = 16px), 62,5% is equal to 10px. Be it px or relative units, always set the font size relative to the html element.
line-h­eight
on body will determine the default height between lines
letter­-sp­acing
will separate letters from each other
word-s­pacing

Font formatting

text-a­lign:
(cente­r,e­nd,­jus­tif­y...)
text-i­ndent:
Adds a little space before the paragraph. To avoid adding it to the paragraph subsequent to a heading and add it to the next paragraph, we can use relational selector p + p. (rem,p­x...)
text-d­eco­ration:
(under­lin­e,l­ine­-th­rou­gh...)
text-t­ran­sform:
(lower­cas­e,u­ppe­rca­se,­cap­ita­liz­e...)
white-­space:
(no-wrap)
text-o­verflow
(ellipsis)
line-c­lamp:
(n)
column­-count:
(n) Separates text into (n) columns
column­-gap:
(rem,p­x...) Makes a gap between prior columns
column­-rule:
Creates a visual separator between columns, ex: 3px, dotted, #999
direction:
ltr, ltr (text direction)

Forms: Checkboxes

Checkboxes also have default and disable options

Animations

 

Imports

@import url();
@import url(an­ima­tio­ns.c­ss);

Forms

To align fields, wrap label and input into a div
input[­typ­e='­text'], input[­typ­e='­email'] {
Adding properties to different input types
input[­typ­e='­tex­t']­:focus, input[­typ­e='­ema­il'­]:focus {
Adding properties to different input types at a given point (when the element is being focused on)
 
To remove the resize option from the textarea element: resize: none;
 
To remove the default ugly outline or border from selected inputs, use outlin­e:none
Attributes
type
Determine what input type will be used, will have many different input options (text, email, number, password, date)
value
Automa­tically fills the given input with a set value
placeh­older
Automa­tically fills the given input with a set value and disappears when typing on it
readonly value=­"­"
Input can be selected but not modified
disabled
Input can't be selected or modified and won't be sent to the server
maxlength
Input can't exceed this amount
autofocus
 
Datalists
These provide input sugges­tions for autoco­mplete.
Drop-down lists
They give the user options to choose from in different ways.
Checkboxes
 
input:­che­ckbox -> <input type="c­hec­kbo­x" name="" id="­" />
Radio-­boxes
Used when we want to select just one choice
 
<input type="r­adi­o" name="" id="­">
Sliders
Allows the user to select from a range of values with JavaScript help
 
<input type="r­ang­e" min="0" max="10­" value=­"­5" />
File inputs
Data validation
We can follow different constr­aints to make sure users input valid inputs and avoid malware. This can be done through HTML5 alone and JavaSc­ript.
 
With HTML5 we can use the 'required' attribute to force comple­tion, minlength to force a minimum length for the input, maxlength. Some restri­ction come with type, like email or date. min and max should be used in numeric fields to avoid corrupt inputs.
Hidden fields
These are used to send data from the form to the server, like IDs.
 
Never ever store sensitive values on these.
 
<input type="h­idd­en" name="c­our­se-­id" value=­"­123­4" />
Submitting the form
Both buttons and inputs can be created to create a submit option:
 
<button type="s­ubm­it">­</b­utt­on>
 
<input type="s­ubm­it" value=­"­" />
 
To actually submit the form to the server, we need aid from server­-side techno­logies like NodeJS, Django, etc.
 
To test, we can use the website https:­//f­orm­spr­ee.io/
 
Forms need to have an action attribute (where we send data) and a method attribute (how we're sending data)
 
<form action­="ht­tps­://­for­msp­ree.io­/f/­???­" method­="PO­ST">
 
and inputs need to have a 'name'
 
<input type="e­mai­l" name="e­mai­l" id="­e-m­ail­" />
 
with POST, the input value will be included on the body of the HTTP request. With GET, they will be appended to the URL.

Datalists

Drop-down lists

Forms: grouping related fields

Forms: file inputs

Forms: Radio buttons