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.
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.
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
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.
Measurement Units
We have measurements that falls into two categories
Absolute | Relative |
---|---|
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:
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).
2. Blur
The blur()
function applies a blur effect to the element. The parameter defines the amount of blur, typically specified in pixels.
Example:
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:
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:
5. Hue-rotate
The hue-rotate()
function rotates the hue of the element. The parameter defines the angle of rotation in degrees.
Example:
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:
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:
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:
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:
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:
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.
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.
3. Skew
The skew()
function skews an element along the X and/or Y-axis. The parameters define the angles of skewing.
4. Translate
The translate()
function moves an element along the X and/or Y-axis. The parameters define the distances of translation.
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.
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.
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:
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:
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:
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:
-
Code Reusability: Variables allow you to define values once and reuse them across your stylesheets, promoting cleaner and more maintainable code.
-
Dynamic Updates: CSS Variables can be updated dynamically, making it easy to change styles, implement theming, or create interactive effects.
-
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.
-
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.
-
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
Child Combinator (>)
Child Combinator (>): Direct Child Elements Only
Adjacent Sibling combinator (+)
Adjacent sibling combinators (+): directly after an element
General Sibling Combinator (~)
General sibling sibling combinators (~): after an element
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.
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.
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.
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.
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.
Pseudo-class vs Pseudo element Selector
Responsive Design
There are 3 key ingredient in a responsive design - [ ] fluid layout - [ ] flexible images - [ ] media queries
Max-width vs Width
Flex Box
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
(frommain-start
tomain-end
) -
➡️ the cross axis (from
cross-start
tocross-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.
flex-direction
This establishes the main-axis, thus defining the direction flex items are placed in the flex container.
- ➡️
row
(default): left to right inltr
; right to left inrtl
- ➡️
row-reverse
: right to left inltr
; left to right inrtl
- ➡️
column
: same asrow
but top to bottom - ➡️
column-reverse
: same asrow-reverse
but bottom to top
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.
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
.
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 thewriting-mode
direction. - ➡️
end
: items are packed toward the end of thewriting-mode
direction. - ➡️
left
: items are packed toward left edge of the container, unless that doesn’t make sense with theflex-direction
, then it behaves likestart
. - ➡️
right
: items are packed toward right edge of the container, unless that doesn’t make sense with theflex-direction
, then it behaves likeend
. - ➡️
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.
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 theflex-direction
rules or thewriting-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 respectingflex-direction
rules vs.writing-mode
rules. - ➡️
center
: items are centered in the cross-axis - ➡️
baseline
: items are aligned such as their baselines align
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 theflex-direction
whilestart
honors thewriting-mode
direction. -
flex-end
/end
: items packed to the end of the container. The (more support)flex-end
honors theflex-direction
while end honors thewriting-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
gap
The gap
property explicitly controls the space between flex items. It applies that spacing only between items not on the outer edges.
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.
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).
flex-shrink
This defines the ability for a flex item to shrink if necessary.
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-content
, min-content
, and fit-content
do.
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.
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
Alignment is Horizontal By default
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.
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.
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
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.
grid-auto-columns and grid-auto-rows
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)
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 withgrid-area
-
.
– a period signifies an empty grid cell -
none
– no grid areas are defined
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
It also accepts a more complex but quite handy syntax for specifying all three. Here’s an example:
That’s equivalent to this:
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
Example:
gap
grid-gap
A shorthand for [row-gap] and [column-gap]
Values:
<grid-row-gap>
<grid-column-gap>
– length values
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)
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 tobaseline
—first baseline
andlast baseline
which will use the baseline from the first or last line in the case of multi-line text.
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 setsalign-items
, the second valuejustify-items
. If the second value is omitted, the first value is assigned to both properties.
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.
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:
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:
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, themax-content
is the length of the whole sentence. -
auto
: this keyword is a lot likefr
units, except that they “lose” the fight in sizing againstfr
units when allocating the remaining space. -
Fractional units: see above
Sizing Functions
-
The
fit-content()
function uses the space available, but never less thanmin-content
and never more thanmax-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:
-
The
min()
function. -
The
max()
function.
The repeat() Function and Keywords
The repeat()
function can save some typing:
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:
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:
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.
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.
CSS Units
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.
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.
Pseudo Class (:link, :visited, :hover, :active ,:focus)
#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 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
We can combine min and max to create a range as well
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:
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.
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.
Selecting elements by their attributes
Using a to select it’s attribute
Object Fit Property
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
Sizing an element
You can use width to size an element but also position does it quite well
Grid vs Flex Alignment
| 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
Center Alignment
Using Position and Transform property
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. Addtop: 50%; left: 50%;
because the position is calculated from the top left corner.
Using Viewport Unit
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
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 tojustify-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.
Using CSS Grid
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
orrem
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.