CSS Units and Viewport
Learn CSS units and viewport measurements for consistency across devices.
Relative units and viewport measurements are essential for creating layouts that can adapt to different devices. In this lesson, we’ll discuss using percentages (%
), em
, rem
, vw
, and vh
units in CSS. We’ll also explore absolute and relative units, discuss how to choose the appropriate units for different scenarios, and learn how to combine units using the calc()
function.
Absolute units
Absolute units are fixed and do not change based on other elements or user settings. They are useful when we need precise control over the size of an element, regardless of the user's environment.
Pixels
Pixels are the most commonly used absolute unit in CSS. One pixel represents one dot on the screen.
.box {width: 200px;height: 100px;background-color: lightblue;}
In the above code:
Line 2: We set the width of the
.box
class to200px
, making it exactly 200 pixels wide.Line 3: The height is set to
100px
, ensuring a fixed height.
Other absolute units
Some other absolute units in CSS, used to define fixed, unchanging sizes for elements regardless of the viewport or screen size, are as follows:
Points (
pt
): Commonly used in print media;1pt
equals 1/72 of an inch.Centimeters (
cm
), millimeters (mm
), inches (in
): Physical measurements; their on-screen size depends on screen resolution.
Note: Due to varying screen resolutions and devices, absolute units other than ...