CSS units are used to specify measurements and sizes in Cascading Style Sheets (CSS). They allow you to define lengths, distances, and other dimensions within a webpage. Here are some commonly used CSS units:
- Pixels (px): Pixels are the most basic unit of measurement in CSS. One pixel represents a single dot on a screen. Pixel values are fixed and do not scale with the user’s device or screen resolution.
- Percentage (%): Percentage units are relative to the parent element. For example, if you set a width of 50% on a child element inside a container, it will take up half of the width of the container.
- Viewport Units (vw, vh, vmin, vmax): Viewport units are relative to the size of the browser window. The available viewport units are:
- vw (viewport width): 1vw is equal to 1% of the width of the viewport.
- vh (viewport height): 1vh is equal to 1% of the height of the viewport.
- vmin: 1vmin is equal to the smaller value between 1vw and 1vh.
- vmax: 1vmax is equal to the larger value between 1vw and 1vh.
- Em (em): The em unit is relative to the font size of the element or its nearest parent with a font size defined. For example, if an element has a font size of 16px, 1em would be equal to 16px. If the font size of a parent element is 20px, 1em would be equal to 20px.
- Rem (rem): The rem unit is similar to the em unit, but it is relative to the root element’s font size (typically the
<html>element). This makes it useful for creating scalable designs across the entire page, as it does not depend on nested elements.
- Absolute Length Units (in, cm, mm, pt, pc): These units represent fixed physical lengths and are typically used for print stylesheets or specific cases where exact measurements are required. For example,
ptrepresents points, and
- Flexible Length Units (fr): The fr unit is used in CSS Grid and CSS Flexbox layouts to distribute available space among multiple elements. It represents a fraction of the available space. For example, if an element has a width of 2fr and another has 1fr, the first element will take twice the space of the second.
These are just a few of the most commonly used CSS units. Each unit has its own purpose and use case, and understanding them allows you to create responsive and flexible designs in CSS.