Home  >  Article  >  Web Front-end  >  Different Kinds of CSS Relative Units

Different Kinds of CSS Relative Units

WBOY
WBOYOriginal
2024-02-18 14:59:06373browse

Different Kinds of CSS Relative Units

There are many types of relative units in CSS, each of which has its applicable scenarios and characteristics. Commonly used relative units are introduced below and some specific code examples are provided.

  1. em
    em is a unit calculated relative to the font-size of the current element. For example, if an element's font-size is 16px, then 1em is equal to 16px. If an element's font size is 2em, then its font size is twice the font size of the parent element.
p {
  font-size: 16px;
}

span {
  font-size: 0.5em; /* 相当于8px */
}
  1. rem
    rem is a unit calculated relative to the font-size size of the root element (that is, the html element). It is used in a similar way to em, but will not be affected by the parent element.
html {
  font-size: 16px;
}

p {
  font-size: 1.5rem; /* 相当于24px */
}
  1. vw/vh
    vw and vh are units relative to the window width and window height. 1vw is equal to 1% of the window width, and 1vh is equal to 1% of the window height. This unit is often used in responsive design to automatically resize elements based on the size of the viewport.
div {
  width: 50vw; /* 相当于视窗宽度的50% */
  height: 30vh; /* 相当于视窗高度的30% */
}
  1. %
    Percentage units are calculated relative to the size of the parent element. For example, if an element has a width of 50%, its width is half the width of its parent element.
.container {
  width: 200px;
}

div {
  width: 50%; /* 相当于100px */
}
  1. ch
    ch is the unit calculated relative to the width of the current font. A ch is equal to the width of the character "0" in the current font.
p {
  font-size: 16px;
}

span {
  width: 10ch; /* 相当于160px */
}

Summary:
Relative units provide a more flexible and adaptable layout method in CSS. Choose the appropriate unit according to your needs. You can choose the appropriate relative unit based on the characteristics of the element and design needs. By rationally using relative units, adaptive layout effects can be achieved.

The above is the detailed content of Different Kinds of CSS Relative Units. 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