There are many relative units in CSS, the common ones are pixel (px), percentage (%), em (em), and rem (rem). These four relative units will be introduced below and specific code examples will be given.
- Pixel (px):
Pixel is a unit relative to the screen resolution. Its value is fixed and will not change according to the user's settings. For example, if you set the width of an element to 100px, its width will remain 100 pixels.
Code example:
div {
width: 100px;
height: 50px;
}
- Percent (%):
Percent is a unit relative to the parent element, and its value will change according to the size of the parent element . In other words, percentage units can automatically adjust the size of elements according to changes in screen size. For example, if the width of the parent element is 200px and you set the width of the child element to 50%, then the child element will occupy half of the width of the parent element.
Code example:
.parent {
width: 200px;
}
.child {
width: 50%;
height: 50px;
}
- em (em):
em is the unit relative to the font size of the element itself. For example, if an element's font size is 16px, then 1em equals 16px, 2em equals 32px, and so on. The em unit can easily realize relative adjustment of font size.
Code example:
p {
font-size: 16px;
}
span {
font-size: 1.5em; /* 相当于24px */
}
- rem (rem):
rem is similar to em, but it is a font relative to the root element (generally referring to html elements) size. The rem unit can uniformly control the font size throughout the entire page, while also enabling relative adjustment.
Code example:
html {
font-size: 16px;
}
p {
font-size: 1.5rem; /* 相当于24px */
}
Summary:
The relative units in CSS are pixel (px), percentage (%), em (em), and rem (rem) . Pixel units are fixed and will not change based on user settings. Percent units change relative to the size of the parent element. Em units are units relative to the font size of the element itself, while rem units are units relative to the font size of the root element. In practical applications, we can choose appropriate relative units to control the size of elements and font sizes as needed.
The above is the detailed content of What are the relative units in css. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn