When styling elements in CSS, you have two categories of units to choose from: absolute units and relative units. Here's a breakdown of each of them and how they differ:
Absolute units are fixed units of measurement. They are not affected by other elements or screen sizes, meaning their size is constant regardless of the context in which they are used.
px (pixels): A pixel is a small square on the screen. It's the most commonly used unit for fixed layouts.
h1 { font-size: 24px; }
pt (points): Typically used in print media, 1pt equals 1/72 of an inch.
cm (centimeters) and in (inches): Rarely used in web design, these units are based on physical dimensions.
Relative units are flexible and scale based on the context they are used in. Their size depends on other elements, such as the parent container, viewport, or base font size.
em: Relative to the font size of the element it’s used on. If the parent element has a font-size of 16px, 1em equals 16px. If the parent element’s size changes, so will the size in em.
p { font-size: 1.5em; /* 1.5 times the font size of the parent */ }
rem (root em): Relative to the font size of the root element (usually the element). This makes it more predictable compared to em.
By default, browsers typically set the root font size to 16px, unless specified otherwise. If you define a custom font size for the element, all rem values will be calculated based on that new size.
Example:
p { font-size: 2rem; /* 2 times the root font size */ }
Example:
div { width: 75%; /* 75% of the parent's width */ }
Example:
div { width: 50vw; /* 50% of the viewport's width */ }
This is 24px text
This is 1.5rem text (24px based on root size)
In this example:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3