135 views
CSS units
In CSS, there are several types of units used to specify measurements for various properties. These units allow you to define sizes, distances, and other dimensions in a way that is flexible and responsive to different screen sizes and devices. Here are the common CSS units:
- Absolute Units:
px
: Pixels are a fixed unit commonly used for defining precise measurements. They provide a consistent size regardless of the screen resolution or device.
- Relative Units:
em
: Relative to the font size of the element. For example,1em
is equivalent to the font size of the element.rem
: Relative to the root element’s font size (usually thehtml
element). It provides a more consistent way to manage relative sizes across the entire document.vw
: Relative to the viewport width.1vw
is 1% of the viewport width.vh
: Relative to the viewport height.1vh
is 1% of the viewport height.vmin
: Relative to the smaller dimension of the viewport (width or height).1vmin
is 1% of the smaller dimension.vmax
: Relative to the larger dimension of the viewport (width or height).1vmax
is 1% of the larger dimension.
- Percentage Units:
%
: Relative to the parent element’s size. For example,50%
is half the size of the parent element.
- Font-relative Units (For Typography):
ex
: The x-height of the element’s font. It is typically about half the height of the lowercase letter “x.”ch
: The width of the “0” (zero) character of the element’s font.cap
: The height of the element’s font capital letters.ic
: The width of the element’s font capital letter “I.”lh
: Line-height. Relative to the element’s font size.
- Angle Units:
deg
: Degrees for rotation or angles.rad
: Radians for rotation or angles.grad
: Gradians for rotation or angles.turn
: A complete turn (360 degrees).
- Time Units:
s
: Seconds.ms
: Milliseconds.
- Resolution Units:
dpi
: Dots per inch.dpcm
: Dots per centimeter.dppx
: Dots per pixel.
Different units are suited for different use cases, and using the appropriate unit can help make your CSS more responsive and adaptable to various devices. When developing responsive designs, relative units like em
, rem
, vw
, vh
, etc., are often preferred over fixed units like px
. This allows elements to scale appropriately based on the user’s device and viewport size.