CSS Units

Types of CSS Units

In CSS, we use units to define the size of elements, and there are two main categories: absolute units and relative units.

Absolute Units:

These are fixed sizes that don’t change based on screen size or other elements:

Tutorials dojo strip
  • px (Pixels): The most common unit, used for on-screen designs. Pixels are small, fixed units of measurement.
CSS
  • in (Inches): Typically used for print layouts, but you probably won’t use this much for web.
CSS
  • cm (Centimeters), mm (Millimeters): Also used in print design. These units aren’t as common in web design.
CSS



Relative Units:

These units change size based on another element, making them more flexible and often better for responsive designs:

  • % (Percentage): The size is relative to the parent element.
CSS
  • em: Relative to the font size of the parent element. If the parent’s font size is 16px, then 1.5em would be 24px.
CSS
  • rem: Similar to em, but relative to the root element (the <html> tag).
CSS
  • vw (Viewport Width): 1vw is equal to 1% of the viewport width (the browser window). This is great for responsive layouts.
CSS
  • vh (Viewport Height): 1vh equals 1% of the viewport height.
CSS




Using Units in CSS

1. Width and Height:

You can define width and height using any of the units mentioned above. For example:

CSS

2. Font Sizes:

Font size is typically defined using px, em, rem, or %, depending on your needs.

CSS

3. Margins and Padding:

You can also set margins and padding using any of these units. This helps control the spacing around and inside elements.

CSS




CSS Units Example Code

CSS




CSS Labs

Tutorials dojo strip