Science Knowings: CSS Course For Social Media

CSS Units

From Box Model to CSS Units

We've explored the CSS Box Model in our previous session. Now, let's delve into CSS Units, the essential tools for defining sizes and positions in CSS.

Types of CSS Units

CSS Units can be classified into four main types: Absolute, Relative, Intrinsic, and Unitless. Each type serves a specific purpose and provides flexibility in defining sizes and positions.

Absolute Units

px, cm, mm, in

Absolute units define fixed, device-independent sizes. They are commonly used for precise positioning and layout.

em & rem Units

em, rem

Relative to the font size of the parent element. em is relative to the current font size, while rem is relative to the root font size. Useful for responsive design.

Percentage (%)

Percentage values define sizes relative to the containing element's dimensions. Commonly used for fluid layouts that adapt to different screen sizes.

vh & vw

Viewport-relative units define sizes relative to the viewport's height (vh) or width (vw). Useful for creating elements that scale with the browser window.

ch & ex

ch is the width of the letter '0' in the current font. ex is the height of the letter 'x' in the current font. Rarely used, but can be useful for precise vertical spacing in typography.

Intrinsic Units

Intrinsic units are based on the element's content. Examples include px (for line height), % (for width based on content width), and intrinsic (for the natural size of an element).

font-size

The font-size property sets the size of the text in an element. It can be specified in absolute units (e.g., px) or relative units (e.g., em).

Converting Between Units

Converting between units is often necessary. Use CSS functions like calc(), rem(), and px() for conversion.

Relative Units

Relative units (em, rem, %) are useful for creating responsive layouts that adapt to different screen sizes and fonts.

Unitless Values

Some CSS properties accept unitless values, such as line-height. These values are relative to the font size of the element.

Which Units to Use

Unit Type When to Use
Absolute Precise positioning, device-independent
Relative Responsive design, scaling with font size
Intrinsic Element content-based sizing
Unitless Font-size relative values

From Units to Pseudo-classes

With a solid understanding of CSS Units, we're now ready to explore CSS Pseudo-classes, a powerful tool for enhancing the interactivity and specificity of CSS rules. Join us for the next session!