CSS Units and Measurements

In CSS, units and measurements play a crucial role in defining the size and spacing of elements on a webpage. Understanding the different units available allows you to create layouts that are both visually appealing and responsive.

Basics

Absolute Length Units

Use fixed units like pixels (px), inches (in), centimeters (cm), millimeters (mm), and points (pt).

				
					/* Set width using pixels */
.box {
  width: 200px;
}

				
			

Relative Length Units

Utilize relative units like percentages (%), ems (em), and rems (rem).

				
					/* Set width as a percentage of the parent container */
.container {
  width: 80%;
}

				
			

Intermediate Usage

Viewport Units

Apply viewport units like 'vw' (viewport width) and 'vh' (viewport height) for responsive design.

				
					/* Set font size based on viewport width */
body {
  font-size: 3vw;
}

				
			

Flexible Box (Flexbox) Units

Utilize flex units like 'fr' within a Flexbox container.

				
					/* Create a flexible layout with Flexbox */
.container {
  display: flex;
}

.item {
  flex: 1; /* Each item takes equal space */
}

				
			

Advanced Techniques

CSS Grid Units

Combine flexible and fixed units within a CSS Grid layout.

				
					/* Create a grid layout with fixed and flexible columns */
.grid-container {
  display: grid;
  grid-template-columns: 1fr 2fr 100px;
}

				
			

Calc Function

Use the 'calc()' function for complex calculations involving different units.

				
					/* Calculate width based on a percentage minus 20 pixels */
.box {
  width: calc(50% - 20px);
}

				
			

CSS units and measurements are pivotal for designing layouts that adapt to different devices and screen sizes. From absolute and relative units to viewport and flexible box units, understanding their use empowers you to create responsive and visually consistent designs. Happy Coding! ❤️

Table of Contents