天天看点

CSS3 px、em、rem 的使用与区别

<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    html {
      font-size: 10px;
    }
    .px {
      font-size: 10px;
      height: 30px;
      background-color: red;
    }
    .em {
      font-size: 1rem;
      height: 2em;
      background-color: pink;
    }
    .rem {
      font-size: 1rem;
      height: 2rem;
      background-color: purple;
    }
  </style>
</head>
<body>
  <div class="px">px 使用当前像素;1px === 1px</div>
  <div class="em">em 使用当前标签的 font-size 作为基准,如果不设置,则以继承父类下来的 font-size 为基准; 1em === 20px</div>
  <div class="rem">rem 使用 html 标签设置的 funt-size 作为基准; 1rem === 10px</div>
</body>
</html>
           
  • demo 效果:
CSS3 px、em、rem 的使用与区别