CSS Units

Home / CSS / CSS Units

CSS Units


CSS-Units:

CSS units are used to measure length, width, height, and other dimensions in web design. They allow you to define the size and positioning of HTML elements within your web page. CSS provides various units, each with its own characteristics. Here are some of the most common CSS units:

Pixels (px):

A pixel is the smallest unit of display on a screen.

It's a fixed unit and provides precise control over element sizes.

Commonly used for setting font sizes and defining exact dimensions.

<style>
    p {
      font-size: 16px;
      width: 200px;
      height: 150px;
    }
  </style>

Percentage (%):

Percentages are relative to the parent element's size or the containing element's size.

Useful for creating responsive designs that adapt to different screen sizes.

<style>
    .container {
      width: 80%;
    }
  </style>

EMS (em):

The "em" unit is relative to the font-size of the parent element.

It's often used for text and allows for scalable and responsive typography.


 <style>
    p {
      font-size: 1.2em;
      /* 1.2 times the font size of the parent element */
    }
  </style>

Rems (rem):

Similar to "em," but relative to the root (the <html> element) font-size.

Useful for creating consistent typography across the entire page.


<style>
    p {
      font-size: 1.2rem;
      /* 1.2 times the root font size */
    }
  </style>

Viewport Units:

These units are relative to the size of the viewport (the visible portion of the web page).

Useful for creating responsive designs based on screen dimensions.


<style>
    .header {
      height: 50vh;
      /* 50% of the viewport height */
    }
  </style>

Centimeters (cm), Millimeters (mm), and Inches (in):

These units allow for physical measurements, such as printing styles.

<style>
    .print-styles {
      margin: 1cm;
      font-size: 0.5in;
    }
  </style>

Points (pt) and Picas (pc):

Typically used for print styles and can also be used for screen styles.

<style>
    .print-heading {
      font-size: 18pt;
    }
  </style>

View Width (vw) and View Height (vh):

These units represent a percentage of the viewport's width or height.

Useful for responsive typography and layouts.


<style>
    h1 {
      font-size: 5vw;
      /* 5% of the viewport width */
    }
  </style>

View Minimum (vmin) and View Maximum (vmax):

These units are relative to the smaller or larger dimension of the viewport (width or height).


 <style>
    .circle {
      width: 20vmin;
      /* 20% of the smaller dimension */
      height: 20vmin;
    }
  </style>