What is CSS:

Cascading Style Sheets is a style sheet language used for describing the presentation of a document written in a markup language such as HTML or XML. CSS is a cornerstone technology of the World Wide Web, alongside HTML and JavaScript

Specificity

Determines how browsers decide which css rule takes precedence

  • 🔖 Universal selector (*) :weak   - [p] Type selector (p,h1…) A bit strong     - 💡 Class (.classname) Strong       - 🔥 id (#example) :Stronger

The Box Model html

In CSS, the term “box model” is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.

div {  width: 300px;
  border: 15px solid green;
  padding: 50px;
  margin: 20px;
}
/**
	320px (width)
	+ 20px (left + right padding)
	+ 10px (left + right border)
	+ 0px (left + right margin)
	**= 350px**
*/

Warning Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.

More convenient way of setting the box sizing

Sometimes you will find yourself doing this, which is a good practice.

*,
*::before,
*::after {
  box-sizing: border-box;
}

CSS Outline

An outline is a line drawn outside the element’s border. CSS has the following outline properties:

  • ➡️ outline-style
    • dotted - Defines a dotted outline
    • dashed - Defines a dashed outline
    • solid - Defines a solid outline
    • double - Defines a double outline
    • groove - Defines a 3D grooved outline
    • ridge - Defines a 3D ridged outline
    • inset - Defines a 3D inset outline
    • outset - Defines a 3D outset outline
    • none - Defines no outline
    • hidden - Defines a hidden outline
  • ➡️ outline-color
  • ➡️ outline-width
  • ➡️ outline-offset
  • ➡️ outline

Outline Short hand

p.ex4  {
  outline: thick ridge pink;
}

Outline Offset

The outline-offset property adds space between an outline and the edge/border of an element. The space between an element and its outline is transparent.

p { 
	margin: 30px;
	border: 1px solid black;
	outline: 1px solid red;
	outline-offset: 15px;
}

Measurement Units

We have measurements that falls into two categories

AbsoluteRelative
Px         %      
pt          vw    
in           vh  
cm          em    
mm          rem    

Image in css

Image types

Raster and vector images are two different types of digital graphics that are used for various purposes. They differ in how they are constructed, stored, and displayed, as well as their characteristics and best use cases.

Raster Images

Raster Images: A raster image is made up of a grid of individual pixels, where each pixel contains color information. These images are resolution-dependent, meaning that they have a fixed number of pixels and their quality is determined by the resolution or pixel density. Popular raster image formats include JPEG, PNG, and GIF.

Vector Images:

A vector image is created using mathematical formulas that define lines, curves, and shapes. Rather than being made up of pixels, vector graphics consist of points and paths that connect them. Vector images are resolution-independent, meaning they can be scaled to any size without losing quality. Common vector image formats include SVG (Scalable Vector Graphics), AI (Adobe Illustrator), and EPS (Encapsulated PostScript).

CSS FILTER

CSS Filter is a powerful feature that allows you to apply visual effects to HTML elements. It provides a wide range of options to manipulate and transform the appearance of images, backgrounds, and even entire elements. Filters can be used to adjust colors, apply blurs, modify brightness, and much more. This guide will explain the various filter functions and their properties.

Applying Filters

Filters are applied to HTML elements using the filter property in CSS. The value of the filter property consists of one or more filter functions separated by spaces. Multiple filters are applied in the order they appear. Here’s an example:

 
.my-element {   filter: grayscale(50%) blur(5px); }
 

In the above example, the element with the class .my-element will have a grayscale effect applied at 50% intensity and a 5-pixel blur effect.

Common Filter Functions

1. Grayscale

The grayscale() function converts an element to grayscale. The parameter specifies the intensity of the effect from 0% (no grayscale) to 100% (complete grayscale).

 
.my-element {   filter: grayscale(50%); }
 

2. Blur

The blur() function applies a blur effect to the element. The parameter defines the amount of blur, typically specified in pixels.

Example:

 
.my-element {   filter: blur(5px); }
 

3. Brightness

The brightness() function adjusts the brightness of the element. A value greater than 1 increases brightness, while a value less than 1 decreases it.

Example:

 
.my-element {   filter: brightness(1.5); }
 

4. Contrast

The contrast() function adjusts the contrast of the element. A value greater than 1 increases contrast, while a value less than 1 decreases it.

Example:

 
.my-element {   filter: contrast(1.2); }
 

5. Hue-rotate

The hue-rotate() function rotates the hue of the element. The parameter defines the angle of rotation in degrees.

Example:

 
.my-element {   filter: hue-rotate(90deg); }
 

6. Invert

The invert() function inverts the colors of the element. The parameter specifies the intensity of inversion from 0% (no inversion) to 100% (complete inversion).

Example:

 
.my-element {   filter: invert(75%); }
 

7. Saturate

The saturate() function adjusts the saturation of the element. A value greater than 1 increases saturation, while a value less than 1 decreases it.

Example:

 
.my-element {   filter: saturate(1.5); }
 

8. Sepia

The sepia() function applies a sepia tone effect to the element. The parameter specifies the intensity of the effect from 0% (no sepia) to 100% (complete sepia).

Example:

 
.my-element {   filter: sepia(30%); }
 

9. Drop-shadow

The drop-shadow() function adds a drop shadow to the element. The parameters define the horizontal offset, vertical offset, blur radius, and optional color of the shadow.

Example:

 
.my-element {   filter: drop-shadow(3px 3px 5px rgba(0, 0, 0, 0.3)); }
 

These are just a few examples of the CSS filter functions available. Each function can be combined and customized to achieve the desired visual effect.

CSS Transformations

CSS Transformations provide a way to modify the position, size, and orientation of HTML elements on the web page. They allow for visually appealing effects and animations by applying various transformations like rotation, scaling, skewing, and translating. This guide will cover the commonly used CSS transformations and their properties.

Applying Transformations

Transformations are applied to HTML elements using the transform property in CSS. The transform property accepts one or more transformation functions, separated by spaces. Here’s an example:

 
.my-element {  
transform: rotate(45deg) scale(1.2) skewX(10deg) translateX(50px);
}
 

In the above example, the element with the class .my-element will be rotated 45 degrees, scaled by 1.2, skewed along the X-axis by 10 degrees, and translated horizontally by 50 pixels.

Common CSS Transformations

1. Rotate

The rotate() function rotates an element clockwise or counterclockwise around a specified point. The parameter defines the angle of rotation.

.my-element {   transform: rotate(45deg); }

2. Scale

The scale() function changes the size of an element by scaling it horizontally and vertically. The parameter specifies the scaling factor. Values greater than 1 increase the size, while values less than 1 decrease it.

.my-element {   transform: scale(1.2); }

3. Skew

The skew() function skews an element along the X and/or Y-axis. The parameters define the angles of skewing.

.my-element {   transform: skewX(10deg) skewY(-5deg); }

4. Translate

The translate() function moves an element along the X and/or Y-axis. The parameters define the distances of translation.

.my-element {   transform: translateX(50px) translateY(-20px); }

5. Multiple Transformations

Multiple transformations can be combined to apply complex effects. The order of transformation functions matters. They are applied from left to right.

 
.my-element {   transform: rotate(30deg) translateX(50px) scale(1.2); }
 

In the above example, the element will be rotated by 30 degrees, translated 50 pixels horizontally, and then scaled by 1.2.

6. Transform Origin

The transform-origin property defines the point around which transformations are performed. It allows you to control the transformation pivot point.

.my-element {   transform-origin: top left; }

In the above example, transformations will occur around the top left corner of the element.

CSS transformations provide powerful ways to manipulate and animate HTML elements, allowing for creative and interactive web designs. Experimenting with different transformation functions and properties can yield visually stunning effects.

CSS Variables

CSS Variables, also known as CSS Custom Properties, allow you to define reusable values in CSS that can be used throughout your stylesheets. They provide a convenient way to manage and update values such as colors, sizes, and other properties across multiple elements. This guide will cover the usage and benefits of CSS Variables.

Defining CSS Variables

CSS Variables are defined using the -- prefix followed by a name and a value. Here’s an example:

:root {
  --primary-color: #007bff;
  --font-size: 16px;
}

In the above example, --primary-color and --font-size are CSS Variables with their respective values.

Using CSS Variables

CSS Variables can be used anywhere in your CSS code by referencing them with the var() function. The var() function takes the variable name as an argument and returns its corresponding value. Here’s an example:

.my-element {  
color: var(--primary-color);  
font-size: var(--font-size); }

In the above example, the --primary-color and --font-size CSS Variables are used to set the color and font-size of the .my-element class.

Updating CSS Variables

One of the main benefits of CSS Variables is the ability to update their values dynamically. This allows for easy theming or changing styles on the fly. To update a CSS Variable, you can use JavaScript to modify the variable value in the style attribute or update the CSS Variable value in a CSS class. Here’s an example:

// Updating CSS Variable with JavaScript
document.documentElement.style.setProperty('--primary-color', '#ff0000');`
/* Updating CSS Variable in a CSS class */
.my-element {
  --primary-color: #ff0000;
}

In both examples, the value of --primary-color is updated to #ff0000.

Cascading and Scoping

CSS Variables follow the cascading and scoping rules of CSS. When a variable is used within a selector, its value will be resolved based on the closest declaration. If a variable is not defined within the current scope, it will be resolved by looking up the parent scopes until it is found or reaches the root element.

Benefits of CSS Variables

CSS Variables offer several benefits:

  1. Code Reusability: Variables allow you to define values once and reuse them across your stylesheets, promoting cleaner and more maintainable code.

  2. Dynamic Updates: CSS Variables can be updated dynamically, making it easy to change styles, implement theming, or create interactive effects.

  3. Consistency: By using variables for common values like colors, font sizes, or spacing, you can ensure consistency and make global style changes with minimal effort.

  4. Responsive Design: CSS Variables can be used in conjunction with media queries to create responsive designs that adapt to different screen sizes or device orientations.

  5. Ease of Maintenance: With CSS Variables, you can update values in one place, making it easier to make changes and maintain your stylesheets.

CSS Variables provide flexibility and enhance the efficiency of CSS development by introducing reusable values and dynamic updates. They are supported by modern browsers and can significantly improve your CSS workflow.

CSS Selectors

ADVANCED SELECTORS

Relation selector

Descendent Selector

Used to select an element in relation to another element

#products p {
  /*Select p inside of the product id*/
}

Child Combinator (>)

Child Combinator (>): Direct Child  Elements Only

article > p {...}
 
/*
<p>...</p>
<article>
  <p>This paragraph will be selected</p>
  <div>
    <p>...</p>
  </div>
</article>
*/

Adjacent Sibling combinator (+)

Adjacent sibling combinators (+): directly after an element

 h1 + p { // Paragraph that direcly follows h1}
 
/*
<p>...</p>
<section>
  <p>...</p>
  <h2>...</h2>
  <p>This paragraph will be selected</p>
  <div>
    <p>...</p>
  </div>
  <p>...</p>
</section>
*/

General Sibling Combinator (~)

General sibling sibling combinators (~):  after an element

 
h1 ~ p { // Paragraph that direcly follows h1}
/\*
 
<p>...</p>
<section>
  <p>...</p>
  <h2>...</h2>
  <p>This paragraph will be selected</p>
  <div>
    <p>...</p>
  </div>
  <p>This paragraph will be selected</p>
</section>
*/

Attribute Selector

Attribute Present Selector

Some of the common selectors looked at early may also be defined as attribute selectors, in which an element is selected based upon its class or ID value. These class and ID attribute selectors are widely used and extremely powerful but only the beginning. Other attribute selectors have emerged over the years, specifically taking a large leap forward with CSS3. Now elements can be selected based on whether an attribute is present and what its value may contain.

Attribute Present Selector The first attribute selector identifies an element based on whether it includes an attribute or not, regardless of any actual value. To select an element based on if an attribute is present or not, include the attribute name in square brackets, [], within a selector. The square brackets may or may not follow any qualifier such as an element type or class, all depending on the level of specificity desired.

a[target] {...}
<a href="#" target="_blank">...</a>

Attribute Equals Selector

To identify an element with a specific, and exact matching, attribute value the same selector from before may be used, however this time inside of the square brackets following the attribute name, include the desired matching value. Inside the square brackets should be the attribute name followed by an equals sign, =, quotations, "", and inside of the quotations should be the desired matching attribute value.

a[href="http://google.com/"] {...}
/*
<a href="http://google.com/">...</a>
*/

Attribute Contains Selector

When looking to find an element based on part of an attribute value, but not an exact match, the asterisk character, *, may be used within the square brackets of a selector. The asterisk should fall just after the attribute name, directly before the equals sign. Doing so denotes that the value to follow only needs to appear, or be contained, within the attribute value.

a[href*="login"] {...}
<a href="/login.js">...</a>

Attribute Begins With Selector

In addition to selecting an element based on if an attribute value contains a stated value, it is also possible to select an element based on what an attribute value begins with. Using a circumflex accent, ^, within the square brackets of a selector between the attribute name and equals sign denotes that the attribute value should begin with the stated value.

a[href^="https://"] {...}
/**<a href="https://chase.com/">...</a>**/

Attribute Spaced Selector

At times attribute values may be spaced apart, in which only one of the words needs to be matched in order to make a selection. In this event using the tilde character, ~, within the square brackets of a selector between the attribute name and equals sign denotes an attribute value that should be whitespace-separated, with one word matching the exact stated value.

a[rel~="tag"] {...}
/** <a href="#" rel="tag nofollow">...</a> **/

Pseudo-class vs Pseudo element Selector  

 
:first-child{}
 
:last-child{}
 
:nth-child(even){
 
/* Select even elements*/
 
}
 
:nth-child(1){
 
/*Select Odd elements*/
 
}
 
:nth-child(3n){
 
    /*every 3rd element*/
 
}
 
:first-of-type{
 
/*select the first of a type of a given element*/
 
}
 
 :last-of-type
 
 {
 
/* Select the first element of a given type.*/
 
 }
 
 
 
 
::first-letter{
 
/*Select the first letter of an element */
 
}
 
::first-line{
 
/*Select the first line of a given paragraph*/
 
}
 
 
 
::selection{
 
 /* Used when you are trying to */
 
}
 
::before{
 
/*Used to add content in a given element.*/
 
}
 

Responsive Design

There are 3 key ingredient in a responsive design  - [ ] fluid layout  - [ ] flexible images  - [ ] media queries

Max-width vs Width

 
section {
 max-width:800px;
 /* as initial , before the browser get resized,*/
 
 width:80%;
 /* applies when the browser has reached a value less than 800px*/
 }

Flex Box

#flex#allignment

Flex box stands for flexible boxes. as crazy as it sounds.

The Flexbox Layout (Flexible Box) module (a W3C Candidate Recommendation as of October 2017) aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic (thus the word “flex”).

Since flexbox is a whole module and not a single property, it involves a lot of things including its whole set of properties. Some of them are meant to be set on :container (parent element, known as “flex container”) whereas the others are meant to be set on the children (said “flex items”).

Items will be laid out following either the :

  • ➡️ main axis (from main-start to main-end)

  • ➡️ the cross axis (from cross-start to cross-end).

  • main axis – The main axis of a flex container is the primary axis along which flex items are laid out. Beware, it is not necessarily horizontal; it depends on the flex-direction property (see below).

  • ➡️   main-start | main-end

    • 🔖 – The flex items are placed within the container starting from main-start and going to main-end.
  • ➡️   main size

    • 🔖 – A flex item’s width or height, whichever is in the main dimension, is the item’s main size. The flex item’s main size property is either the ‘width’ or ‘height’ property, whichever is in the main dimension.
  • ➡️   cross axis

    • 🔖 – The axis perpendicular to the main axis is called the cross axis. Its direction depends on the main axis direction.
  • ➡️   cross-start | cross-end

    • 🔖 – Flex lines are filled with items and placed into the container starting on the cross-start side of the flex container and going toward the cross-end side.
  • ➡️   cross size

    • 🔖 – The width or height of a flex item, whichever is in the cross dimension, is the item’s cross size. The cross size property is whichever of ‘width’ or ‘height’ that is in the cross dimension.

Flex Box Properties

Flex box has a whole variety of properties, but those properties can be categorized into two main categories.

  • 🔥 Properties for the parent Flex Container
  • 🔥 Property of the child flex container

Properties for the Parent Flex Container

display

This defines a flex container; inline or block depending on the given value. It enables a flex context for all its direct children.

.container {
  display: flex; /* or inline-flex */
}
flex-direction

This establishes the main-axis, thus defining the direction flex items are placed in the flex container.

  • ➡️   row (default): left to right in ltr; right to left in rtl
  • ➡️   row-reverse: right to left in ltr; left to right in rtl
  • ➡️   column: same as row but top to bottom
  • ➡️   column-reverse: same as row-reverse but bottom to top
.container {
flex-direction: row | row-reverse |
				column | column-reverse;
}

flex-wrap

By default, flex items will all try to fit onto one line. You can change that and allow the items to wrap as needed with this property.

  • ➡️   nowrap (default): all flex items will be on one line
  • ➡️   wrap: flex items will wrap onto multiple lines, from top to bottom.
  • ➡️   wrap-reverse: flex items will wrap onto multiple lines from bottom to top.
 
.container { flex-wrap: nowrap | wrap | wrap-reverse; }
 
flex-flow

This is a shorthand for the flex-direction and flex-wrap properties, which together define the flex container’s main and cross axes. The default value is row nowrap.

 
.container {
  flex-flow: column wrap;
}
 
justify-content

This defines the alignment along the main axis. It helps distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line.

  • ➡️   flex-start (default): items are packed toward the start of the flex-direction.
  • ➡️   flex-end: items are packed toward the end of the flex-direction.
  • ➡️   start: items are packed toward the start of the writing-mode direction.
  • ➡️   end: items are packed toward the end of the writing-mode direction.
  • ➡️   left: items are packed toward left edge of the container, unless that doesn’t make sense with the flex-direction, then it behaves like start.
  • ➡️   right: items are packed toward right edge of the container, unless that doesn’t make sense with the flex-direction, then it behaves like end.
  • ➡️   center: items are centered along the line
  • ➡️   space-between: items are evenly distributed in the line; first item is on the start line, last item on the end line
  • ➡️   space-around: items are evenly distributed in the line with equal space around them. Note that visually the spaces aren’t equal, since all the items have equal space on both sides. The first item will have one unit of space against the container edge, but two units of space between the next item because that next item has its own spacing that applies.
  • ➡️   space-evenly: items are distributed so that the spacing between any two items (and the space to the edges) is equal.
 
.container {
 
justify-content: flex-start | flex-end | center | space-between | space-around |
 
         space-evenly | start | end | left | right ... + safe | unsafe;
 
}
 

align-items

This defines the default behavior for how flex items are laid out along the cross axis on the current line. Think of it as the justify-content version for the cross-axis (perpendicular to the main-axis).

  • ➡️   stretch (default): stretch to fill the container (still respect min-width/max-width)
  • ➡️   flex-start / start / self-start: items are placed at the start of the cross axis. The difference between these is subtle, and is about respecting the flex-direction rules or the writing-mode rules.
  • ➡️   flex-end / end / self-end: items are placed at the end of the cross axis. The difference again is subtle and is about respecting flex-direction rules vs. writing-mode rules.
  • ➡️   center: items are centered in the cross-axis
  • ➡️   baseline: items are aligned such as their baselines align
 
.container {
 
align-items: stretch | flex-start | flex-end | center | baseline | first baseline |
 
      last baseline | start | end | self-start | self-end + ... safe | unsafe;
 
}
 

align-content

This aligns a flex container’s lines within when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis.

  • normal (default): items are packed in their default position as if no value was set.

  • flex-start / start: items packed to the start of the container. The (more supported) flex-start honors the flex-direction while start honors the writing-mode direction.

  • flex-end / end: items packed to the end of the container. The (more support) flex-end honors the flex-direction while end honors the writing-mode direction.

  • center: items centered in the container

  • space-between: items evenly distributed; the first line is at the start of the container while the last one is at the end

  • space-around: items evenly distributed with equal space around each line

  • space-evenly: items are evenly distributed with equal space around them

  • stretch: lines stretch to take up the remaining space

 
.container { align-content: flex-start | flex-end | center | space-between | space-around |
 
space-evenly | stretch | start | end | baseline | first baseline | last baseline + ... safe | unsafe;
 
  }
 

gap

The gap property explicitly controls the space between flex items. It applies that spacing only between items not on the outer edges.

 
.container {
 
display: flex;
 
...
 
gap: 10px;
 
gap: 10px 20px; /* row-gap column gap */
 
row-gap: 10px; column-gap: 20px;
 
}
 

Properties for the Child Flex Container(flex items)

order

By default, flex items are laid out in the source order. However, the order property controls the order in which they appear in the flex container.

 
.item { order: 5; /* default is 0 */ }
 
flex-grow

This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.

If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. If one of the children has a value of 2, that child would take up twice as much of the space either one of the others (or it will try, at least).

 
.item { flex-grow: 4; /* default 0 */ }
 
flex-shrink

This defines the ability for a flex item to shrink if necessary.

 
.item { flex-shrink: 3; /* default 1 */ }
 
flex-basis

This defines the default size of an element before the remaining space is distributed. It can be a length (e.g. 20%, 5rem, etc.) or a keyword. The auto keyword means “look at my width or height property” (which was temporarily done by the main-size keyword until deprecated). The content keyword means “size it based on the item’s content” – this keyword isn’t well supported yet, so it’s hard to test and harder to know what its brethren max-contentmin-content, and fit-content do.

 
.item { flex-basis: | auto; /* default auto */ }
 
flex

This is the shorthand for flex-grow, flex-shrink and flex-basis combined. The second and third parameters (flex-shrink and flex-basis) are optional.

The default is 0 1 auto, but if you set it with a single number value, like flex: 5;, that changes the flex-basis to 0%, so it’s like setting flex-grow: 5; flex-shrink: 1; flex-basis: 0%;.

align-self

This allows the default alignment (or the one specified by align-items) to be overridden for individual flex items.

Please see the align-items explanation to understand the available values.

 
.item {
 
  align-self: auto | flex-start | flex-end | center | baseline | stretch;
 
  }
 

Both flexbox and grid can be used for layout but : flexbox: Is great for space Distribution across a single axis

FLEXBOX

Flex Container:Refers to the parent Element

Flex items: The Direct child elements within the flex container

<section class="flex-container">
  <div>
    {" "}
    flex item
    <div> Not a flex item</div>
  </div>
 
  <div>flex item</div>
 
  <div>flex item</div>
 
  <div>flex item</div>
</section>

Alignment is Horizontal By default

 
.flex-container{
 
    background-color:cornflowerblue;
 
    display: inline-flex;
 
}
 
 
 
<section class="flex-container">
 
        <div> flex item</div>
 
       <div>flex item</div>
 
       <div>flex item</div>
 
       <div>flex item</div>
 
    </section>
 

CSS GRID

CSS Grid Layout (aka “Grid” or “CSS Grid”), is a two-dimensional grid-based layout system that, compared to any web layout system of the past, completely changes the way we design user interfaces. CSS has always been used to layout our web pages, but it’s never done a very good job of it. First, we used tables, then floats, positioning and inline-block, but all of these methods were essentially hacks and left out a lot of important functionality (vertical centering, for instance). Flexbox is also a very great layout tool, but its one-directional flow has different use cases — and they actually work together quite well! Grid is the very first CSS module created specifically to solve the layout problems we’ve all been hacking our way around for as long as we’ve been making websites.

Grid Terminology

Before diving into the concepts of Grid it’s important to understand the terminology. Since the terms involved here are all kinda conceptually similar, it’s easy to confuse them with one another if you don’t first memorize their meanings defined by the Grid specification. But don’t worry, there aren’t many of them.

Grid container

The element on which display: grid is applied. It’s the direct parent of all the grid items. In this example container is the grid container.

<div class="container">
  <div class="item item-1"></div>
  <div class="item item-2"></div>
  <div class="item item-3"></div>
</div>

Grid Line

The dividing lines that make up the structure of the grid. They can be either vertical (“column grid lines”) or horizontal (“row grid lines”) and reside on either side of a row or column. Here the yellow line is an example of a column grid line.

Grid Track

The space between two adjacent grid lines. You can think of them as the columns or rows of the grid. Here’s the grid track between the second and third-row grid lines.

Grid Area

The total space surrounded by four grid lines. A grid area may be composed of any number of grid cells. Here’s the grid area between row grid lines 1 and 3, and column grid lines 1 and 3.

Grid Item

The children (i.e. direct descendants) of the grid container. Here the item elements are grid items, but sub-item isn’t.

<div class="container">
   
  <div class="item">   </div>
  <div class="item">
         
    <p class="sub-item"></p>
 
       
  </div>
  <div class="item"> </div>
</div>

Grid Cell

The space between two adjacent row and two adjacent column grid lines. It’s a single “unit” of the grid. Here’s the grid cell between row grid lines 1 and 2, and column grid lines 2 and 3.

GRID Property for the parent (Grid Container)

display

Defines the element as a grid container and establishes a new grid formatting context for its contents.

  • grid – generates a block-level grid

  • inline-grid – generates an inline-level grid

.container {
  display: grid | inline-grid;
}

grid-template-columns  and grid-template-rows

Defines the columns and rows of the grid with a space-separated list of values. The values represent the track size, and the space between them represents the grid line.

 
.container {
 
grid-template-columns: ... ...;
 
grid-template-columns:
 
/* e.g.
 
1fr 1fr minmax(10px, 1fr)
 
3fr repeat(5, 1fr) 50px auto 100px 1fr
 
*/
 
grid-template-rows: ... ...;
 
/* e.g. min-content 1fr min-content 100px 1fr max-content */
 
}
 

grid-auto-columns and  grid-auto-rows

#height#autohight

They Specifies the size of any auto-generated grid tracks (aka implicit grid tracks). Implicit tracks get created when there are more grid items than cells in the grid or when a grid item is placed outside of the explicit grid. (see The Difference Between Explicit and Implicit Grids)

.container {
  grid-auto-columns: <track-size>...;
 
  grid-auto-rows: <track-size>...;
 
  grid-auto-rows: 300px; /* The row height is 300px all rows shoule be this way*/
 
  grid-auto-rows: minmax(
    300px,
    auto
  ); /* By default rows are 300px but if there is longer content in a given row then extend it.*/
}

grid-template-areas

Defines a grid template by referencing the names of the grid areas which are specified with the [grid-area](https://css-tricks.com/snippets/css/complete-guide-grid/#prop-grid-area) property. Repeating the name of a grid area causes the content to span those cells. A period signifies an empty cell. The syntax itself provides a visualization of the structure of the grid.

  • <grid-area-name> – the name of a grid area specified with grid-area

  • . – a period signifies an empty grid cell

  • none – no grid areas are defined

 
.container {
 
  grid-template-areas:
 
    "<grid-area-name> | . | none | ..."
 
    "...";
 
}
 
 
.item-a { grid-area: header; }
 
.item-b { grid-area: main; }
 
.item-c { grid-area: sidebar; }
 
.item-d { grid-area: footer; }
 
.container {
 
display: grid;
 
 
 
grid-template-columns: 50px 50px 50px 50px;
 
 
 
grid-template-rows: auto;
 
 
 
grid-template-areas:
 
  "header header header header"
 
  "main main . sidebar"
 
  "footer footer footer footer";
 
}
 

That’ll create a grid that’s four columns wide by three rows tall. The entire top row will be composed of the header area. The middle row will be composed of two main areas, one empty cell, and one sidebar area. The last row is all footer.

grid-template

A shorthand for setting `[grid-template-rows] [grid-template-columns] and [grid-template-areas] in a single declaration.

Values:

  • none – sets all three properties to their initial values

  • <grid-template-rows> / <grid-template-columns> – sets [grid-template-columns] and [grid-template-rows] to the specified values, respectively, and sets to none

.container {
  grid-template: none | <grid-template-rows> / <grid-template-columns>;
}

It also accepts a more complex but quite handy syntax for specifying all three. Here’s an example:

 
.container {
 
  grid-template:
 
[row1-start] "header header header" 25px [row1-end]
 
[row2-start] "footer footer footer" 25px [row2-end]
 
    / auto 50px auto;
 
}
 

That’s equivalent to this:

 
.container {
 
  grid-template-rows: [row1-start] 25px [row1-end row2-start] 25px [row2-end];
 
  grid-template-columns: auto 50px auto;
 
  grid-template-areas:
 
    "header header header"
 
    "footer footer footer";
 
}
 

column-gap, row-gap, grid-column-gap,grid-row-gap

Specifies the size of the grid lines. You can think of it like setting the width of the gutters between the columns/rows

.container {
  /* standard */
 
  column-gap: <line-size>;
 
  row-gap: <line-size>;
 
  /* old */
 
  grid-column-gap: <line-size>;
 
  grid-row-gap: <line-size>;
}

Example:

 
.container {
 
  grid-template-columns: 100px 50px 100px;
 
  grid-template-rows: 80px auto 80px;
 
  column-gap: 10px;
 
  row-gap: 15px;
 
}
 

gap  

grid-gap

A shorthand for [row-gap] and [column-gap]

Values:

  • <grid-row-gap> <grid-column-gap> – length values
 
.container {
 
  /* standard */
 
  gap: <grid-row-gap> <grid-column-gap>;
 
  /* old */
 
  grid-gap: <grid-row-gap> <grid-column-gap>;
 
}
 

justify-items

Aligns grid items along the inline (row) axis (as opposed to [align-items](https://css-tricks.com/snippets/css/complete-guide-grid/#prop-align-items) which aligns along the block (column) axis). This value applies to all grid items inside the container.

Values:

  • start – aligns items to be flush with the start edge of their cell

  • end – aligns items to be flush with the end edge of their cell

  • center – aligns items in the center of their cell

  • stretch – fills the whole width of the cell (this is the default)

 
.container {
 
  justify-items: start | end | center | stretch;
 
}
 

align-items

Aligns grid items along the block (column) axis (as opposed to [justify-items](https://css-tricks.com/snippets/css/complete-guide-grid/#prop-justify-items) which aligns along the inline (row) axis). This value applies to all grid items inside the container.

Values:

  • stretch – fills the whole height of the cell (this is the default)

  • start – aligns items to be flush with the start edge of their cell

  • end – aligns items to be flush with the end edge of their cell

  • center – aligns items in the center of their cell

  • baseline – align items along text baseline. There are modifiers to baseline — first baseline and last baseline which will use the baseline from the first or last line in the case of multi-line text.

 
.container {
 
  align-items: start | end | center | stretch;
 
}
 

place-items

place-items sets both the align-items and justify-items properties in a single declaration.

Values:

  • <align-items> / <justify-items> – The first value sets align-items, the second value justify-items. If the second value is omitted, the first value is assigned to both properties.
.center {
  display: grid;
 
  place-items: center;
}

Properties for the children(grid Items)

grid-column-start, grid-column-end, grid-row-start, grid-row-end

Determines a grid item’s location within the grid by referring to specific grid lines. grid-column-start/grid-row-start is the line where the item begins, and grid-column-end/grid-row-end is the line where the item ends.

 
.item {
 
  grid-column-start: <number> | <name> | span <number> | span <name> | auto;
 
  grid-column-end: <number> | <name> | span <number> | span <name> | auto;
 
  grid-row-start: <number> | <name> | span <number> | span <name> | auto;
 
  grid-row-end: <number> | <name> | span <number> | span <name> | auto;
 
}
 
//or
 
.item-a {
 
  grid-column-start: 2;
 
  grid-column-end: five;
 
  grid-row-start: row1-start;
 
  grid-row-end: 3;
 
}
 
 
 
//Or
 
 
 
.item {
 
  grid-column: 2 / span 3;
 
  grid-row: 1 / span 2;
 
}
 
 
 

Special Units & Functions

fr units

You’ll likely end up using a lot of fractional units in CSS Grid, like 1fr. They essentially mean “portion of the remaining space”.

So a declaration like:

grid-template-columns: 1fr 3fr;

Means, loosely, 25% 75%. Except that those percentage values are much more firm than fractional units are. For example, if you added padding to those percentage-based columns, now you’ve broken 100% width (assuming a content-box box model). Fractional units also much more friendly in combination with other units, as you can imagine:

grid-template-columns: 50px min-content 1fr;

Sizing Keywords

When sizing rows and columns, you can use all the lengths you are used to, like px, rem, %, etc, but you also have keywords:

  • min-content: the minimum size of the content. Imagine a line of text like “E pluribus unum”, the min-content is likely the width of the word “pluribus”.

  • max-content: the maximum size of the content. Imagine the sentence above, the max-content is the length of the whole sentence.

  • auto: this keyword is a lot like fr units, except that they “lose” the fight in sizing against fr units when allocating the remaining space.

  • Fractional units: see above

Sizing Functions

  • The fit-content() function uses the space available, but never less than min-content and never more than max-content.

  • The minmax() function does exactly what it seems like: it sets a minimum and maximum value for what the length is able to be. This is useful for in combination with relative units. Like you may want a column to be only able to shrink so far. This is extremely useful and probably what you want:

grid-template-columns: minmax(100px, 1fr) 3fr;
  • The min() function.

  • The max() function.

The repeat() Function and Keywords

The repeat() function can save some typing:

grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
 
/* easier: */
 
grid-template-columns: repeat(8, 1fr);
 
/* especially when: */
 
grid-template-columns: repeat(8, minmax(10px, 1fr));

But repeat() can get extra fancy when combined with keywords:

  • auto-fill: Fit as many possible columns as possible on a row, even if they are empty.

  • auto-fit: Fit whatever columns there are into the space. Prefer expanding columns to fill space rather than empty columns.

This bears the most famous snippet in all of CSS Grid and one of the all-time great CSS tricks:

grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));

The difference between the keywords is spelled out in detail here.

Masonry

An experimental feature of CSS grid is masonry layout. Note that there are lots of approaches to CSS masonry, but mostly of them are trickery and either have major downsides or aren’t what you quite expect.

The spec has an official way now, and this is behind a flag in Firefox:

 
.container {
 
  display: grid;
 
  grid-template-columns: repeat(4, 1fr);
 
  grid-template-rows: masonry;
 
}
 

See Rachel’s article for a deep dive.

Subgrid

Subgrid is an extremely useful feature of grids that allows grid items to have a grid of their own that inherits grid lines from the parent grid.

 
.parent-grid {
 
  display: grid;
 
  grid-template-columns: repeat(9, 1fr);
 
}
 
.grid-item {
 
  grid-column: 2 / 7;
 
 
 
  display: grid;
 
  grid-template-columns: subgrid;
 
}
 
.child-of-grid-item {
 
  /* gets to participate on parent grid! */
 
  grid-column: 3 / 6;
 
}
 

This is only supported in Firefox right now, but it really needs to get everywhere.

It’s also useful to know about display: contents;. This is not the same as subgrid, but it can be a useful tool sometimes in a similar fashion.

<div class="grid-parent">
   
  <div class="grid-item"></div>
 
   
  <div class="grid-item"></div>
 
   
  <ul style="display: contents;">
       
    <!-- These grid-items get to participate on
 
         the same grid!-->
 
       
    <li class="grid-item"></li>
 
       
    <li class="grid-item"></li>
 
     
  </ul>
</div>

CSS Units

#rem#em#px

px

(pixel) is an absolute unit and is not scalable. It always stays the same size, regardless of the screen size or the user’s preferences. This makes it a good choice for small, fixed-size elements like borders, but it can cause problems with accessibility and responsiveness.

em

(em) is a relative unit that is based on the font size of the parent element. It can be useful for creating scalable typography, but it can also be unpredictable when nested inside multiple elements with varying font sizes.

rem 

(root em) is a relative unit that is based on the font size of the root element (which is typically the html element). Unlike em, it is not affected by the font size of the parent element. This makes it a good choice for creating scalable typography and responsive layouts.

Using em

An em value is equal to the computed font-size of the parent of that element.E. g.if there is a

div (https://www.w3docs.com/learn-html/html-div-tag.html)

element having font-size: 16px then 1em=16px for the div and its child elements. When the font-size isn’t specified explicitly, that element will inherit it from the parent element. This inheritance continues up until the root element. The root element’s font-size is provided by the browser.

 
<style>
 
.content-container{ font-size: 20px; }
 
.content { font-size: 1.5em; }
 
</style>
 
 
 
<div id="content-container" class="content-container">
 
  Parent element
 
  <div id="outerChild" class="content">
 
    Outer child element
 
    <div id="innerChild" class="content">
 
       Inner child element
 
     </div>
 
  </div>
 
</div>
 

Using rem values

The rem values are relative to the root HTML element. If the root element’s font-size: 16px, 1rem = 16px for all elements. If the font-size isn’t defined explicitly in the root element, 1rem will be equal to the default font-size which is provided by the browser.

Which one to use when

  • Use px for small, fixed-size elements like borders or shadows.
  • Use em for typography and other scalable elements that need to change size relative to their parent element.
  • Use rem for scalable typography and responsive layouts that need to change size relative to the root element.

#link#visited#hover#active#focusjs

//change the color of a link

a:link{

color:green;

}

//Link after being clicked

a:visited{

color: gray;

}

//The first two ones , only appy to links while the others apply to any other element

//when navigating with tab

a:focus{

border :1px solid back;

}

//apply when hovering

a:hover{

color:red;

}

//apply when there is a press and release of a mouse

a:ac tive{

color:red;

}




## Relative Length unit

```js

em:represents inherited font-size of element



rem:represent the font-size of the root element

Media Queries

 
/ @media_rule  media_type     media_feature*/
 
@media screen and (max-width: 1000px){
 
  h1{
 
  font-size:16px;
 
  }
 
}
 
 
 
/*When the browser viewport is smaller than 1000px apply this styles
 
 
 

Media Queries Width Break Points

Two to four are generally used

  • 320px: Mobile Portrait

  • 480px:Mobile Landscape

  • 600px: small tabet

  • 768px: tablet Portrait

  • 940-1024px: tablet Landscape

  • 1280px: Destop Laptop screen

 
/*Exact width */
 
@media (width: 360){ ... }
 
 
 
/* Minimum width -360 or larger */
 
@media (min-width:360px) { ... }
 
 
 
/* Maximum width - 360 or smaller */
 
@media (max-width:360px) { ... }  
 
We can combine min and max to create a range as well
 
@media (max-width:360px)  and (max-width:800px) { ... }
 

There is two ways we can do responsiveness

  • Desktop first : usually uses max-width

  • mobile first : usually uses min-width

CSS TIPS

Semantic Elements

  • article: Defines an independent, self-contained content
  • aside: Defines content aside from the content (like a sidebar)
  • details: Defines additional details that the user can open and close on demand
  • figcaption:
  • figure:
  • footer: Defines a footer for a document or a section
  • header: Defines a header for a document or a section
  • main:
  • mark:
  • nav: Defines a set of navigation links
  • section: Defines a section in a document
  • summary: Defines a heading for the <details> element
  • time:

Max-width for the image:

 
/*This will make sure that the image never goes beyong it's container , at best it can only be 100%
 
img{
 
  max-width: 100%;
}
 

box-model fix

ince the dawn of CSS, the box model has worked like this by default:

width + padding + border = actual visible/rendered width of an element’s box

height + padding + border = actual visible/rendered height of an element’s box

This can be a little counter-intuitive, since the width and height you set for an element both go out the window as soon as you start adding padding and borders to the element.

 
html{
 
box-sizing:border-box;
 
}
 
*, *:before, *:after{
 
box-sizing:inherit;
 
}
 

Clear Fix hack (added on the parent element)

The clearfix, for those unaware, is a CSS hack that solves a persistent bug that occurs when two floated elements are stacked next to each other. When elements are aligned this way, the parent container ends up with a height of 0, and it can easily wreak havoc on a layout.

 
 
 
<div class="clearfix">
 
  <div class="child">child</div>
 
  <div class="child">child</div>
 
</div>
 
 
 
.clearfix:after{
 
content: "";
 
display:table;
 
clear:both;
 
}
 
 
 

Selecting elements by their attributes

Using a to select it’s attribute

 
<style>
 
  a[target]{ ... } // all a elements that have the target attribute
 
  a[target='_blank']{ ... } // we can be specific too
 
  a[href='https://google.com']{ ... } // this code is very fragile
 
  a[href*='google.com']{ ... } // much more flexible (any link with that in it)
 
  a[href$='.com']{ ... } // All Links that ends with..
 
  a[href$='.com']{ ... } // All Links that ends with..
 
  a[href$='https'][href$='.com']{ ... }// Combining selectors
 
</style>
 
<a href="https://google.com" target="_blank">Google</a>
 

Object Fit Property

#object-fit

This property is applied to images mostly to make the fit even after resizing

The replaced content is sized to maintain its aspect ratio while filling the element’s entire content

 
<style>
 
img{
 
  object-fit:cover;
 
}
 
</style>
 

Sizing an element

You can use width to size an element but also position does it quite well

 
.container .item:nth-child(1) {
  background-color: dodgerblue;
  position: relative;
  left: 4rem;
  top: 4rem;
  width: auto;
/*Will be as big as it can and leave 4rem both on left and right*/
}
 

Grid vs Flex Alignment

 
justify-content: space-between /*Main Axis*/; <=> justify-items:center /*Horizontal Acciss*/;
 
align-items: center /*Cross Axis*/; <=> align-items /*Along the vertical axis*/
 

| Flex Box Alignment                                           | Grid Alignment                                                  |

| ------------------------------------------------------------ | --------------------------------------------------------------- |

| justify-content: space-between; Align in the main axis | justify-items:center; Horizontal axis                     |

| align-items: center; Cross Axis                        | align-items:center; Along the vertical axis               |

|                                                              | justify-content:center; align the whole grid(item holder) |

|                                                              | align-content:center; align grid vertically                                                                |

Data list

You want users to input content that they want but would still want to suggest them something ? that is when a data list comes in play

 
<label for="browser">Choose your browser from the list:</label>  
 
<input list="browsers" name="browser" id="browser">  
 
<datalist id="browsers">  
  <option value="Edge">  
  <option value="Firefox">  
  <option value="Chrome">  
  <option value="Opera">  
  <option value="Safari">  
</datalist>

Center Alignment

Using Position and Transform property

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

These properties are set on the child element. Absolute positioning bases the element’s position relative to the nearest parent element that has position: relative. If it can’t find one, it will be relative to the document. Add top: 50%; left: 50%; because the position is calculated from the top left corner.

Using Viewport Unit

.child {
  margin: 50vh auto 0;
  transform: translateY(-50%);
}

We use the margin-left/margin-right: auto; for the horizontal centering and use the relative vh value for the vertical centering. Of course, you have to pull back the item like in the absolute example (but only translate the height). _Note :- This method only works if you are positioning to the main viewport.

Using Flexbox

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

Setting the parent(or container) to display: flex; it let the browser know that we intend the children to use flexbox for their layout. Justify-content determines how to space your content in your row or column. Align-content is similar to justify-content, but controls where the items are on the cross axis.

Instead of using justify-content and align-items we can use margin: auto; in child.

.parent {
  display: flex;
  min-height: 100vh;
}
.child {
  margin: auto;
}

Using CSS Grid

.parent {
  display: grid;
  grid-template-rows: 100vh;
  grid-template-columns: 100vw;
}
.child {
  justify-self: center;
  align-self: center;
}

On the parent set display: grid;and specify the row/column width. On the child set the justify-self and align-self to center. The justify-self and align-self property set the way a box is justified inside its alignment container(parent) along the appropriate axis.

Rem Vs Em

CSS (Cascading Style Sheets) is a fundamental part of web development, and having a strong grasp of its intricacies is crucial for any programmer. In this discussion, we’ll delve into the difference between two commonly used units in CSS: em and rem. These units are essential when defining sizes in your stylesheets and can significantly impact the responsiveness and scalability of your web designs.

What are em and rem Units?

em Unit

  • The em unit is a relative length unit in CSS. It is relative to the font size of its parent element.
  • When you specify a size using em, it scales with respect to the font size of the nearest parent element that has a defined font size.
  • For example, if the font size of the parent element is 16px, and you set the font size of a child element to 1.5em, it would be 24px (1.5 times the parent’s font size).

rem Unit

  • The rem unit is also a relative length unit, but it’s relative to the root (html) element’s font size.
  • Unlike em, rem maintains a consistent reference point – the font size of the root element – throughout your CSS. This makes it useful for creating scalable and more predictable designs.

Why Use rem Over em?

Predictability

One of the primary reasons to favor rem over em is predictability. When you use rem, you don’t have to worry about the cascade of font size changes from parent to child elements. It ensures that text and elements maintain consistent proportions and are easier to control.

Ease of Scaling

rem simplifies scaling in your designs. If you change the font size of the root element, all rem-based sizes will adjust accordingly. This is especially useful for responsive web design, where you might change the root font size for different screen sizes.

Accessibility

Using rem units can enhance accessibility. Users who rely on browser settings to increase text size will have a more consistent experience when rem units are employed. em units can lead to unpredictable text sizing in such scenarios.

Best Practices

Here are some best practices to keep in mind:

  • Use rem for global typography (e.g., body text) to ensure consistency.
  • Use em for local adjustments, where sizing should be relative to the parent element.
  • Maintain a balanced approach, choosing em or rem based on your specific design needs.

Gotchas

  • Avoid deep nesting of em units, as it can lead to compounding font sizes that are challenging to manage.
  • Be mindful of overusing rem for everything, as it might result in overly rigid designs. Balance is key.

Conclusion

In the world of CSS, understanding the difference between em and rem units is a valuable skill. While both have their use cases, rem is often favored for its predictability, scalability, and accessibility benefits. Incorporating these units effectively in your stylesheets can contribute to more robust and responsive web designs.

Feel free to ask any questions or delve deeper into specific CSS topics. Your commitment to learning and mastering web development is commendable, and it’s a great step toward achieving your goal of becoming a senior developer in the near future.