CSS Units
In CSS, units are used to specify the size of various properties such as length, width, margin, padding, font size, etc. There are different types of units that can be used in CSS. In this tutorial, we will learn about some commonly used CSS units and how to use them in our stylesheets.
Absolute Units
Absolute units are fixed in relation to physical units of measurement. They are not recommended for use on the web because they do not scale well across different devices and screen sizes. Some examples of absolute units include:
| Unit | Description |
|---|---|
| cm | Centimeters |
| mm | Millimeters |
| in | Inches |
| pt | Points (1/72 of an inch) |
Relative Units
Relative units are more flexible as they scale with the size of the parent element or viewport. They are commonly used in web design to create responsive layouts. Some examples of relative units include:
| Unit | Description |
|---|---|
| em | Relative to the font size of the element |
| rem | Relative to the font size of the root element |
| % | Percentage of the parent element |
| vw | Relative to 1% of the viewport width |
| vh | Relative to 1% of the viewport height |
Here is an example of how to use relative units in CSS:
.container {
width: 80%;
font-size: 1.2em;
padding: 2rem;
}
In the example above, the width of the container is set to 80% of its parent element, the font size is 1.2 times the font size of the parent element, and the padding is 2 times the font size of the root element.
By using relative units, you can create layouts that adapt to different screen sizes and devices, making your website more responsive and user-friendly.