Skip to content

像素和百分比

显示器是由一个个小方格组成的 不同屏幕的像素的大小是不同的,像素点越小的屏幕越清晰。 所以同样的200px在不同 的设备下显示效果不一样。

像素的单位

px表示像素:

200px 300px

百分比

将属性值设置为相对于父元素的百分比 例子: 后面两个.box2的效果是一样的

html
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1{
            width: 200px;
            height: 200px;
            background-color: turquoise;
        }
        .box2{
            width: 100px;
            height: 100px;
            background-color: yellow;
        }
        .box2{
            width: 50%;
            height: 50%;
            background-color: yellow;
        }
/* 后面两个.box2的效果是一样的 */
    </style>
</head>
<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>
</html>

em和rem

em是相对于自身字体大小大小来计算的 1em=1font-size(默认为16) rem是相对于根元素(html)字体大小来计算的(移动端用的多) 例:

css
.box3{
           font-size: 30px;
           width: 10em;
           /* 相当于300px */
           height: 10em;
           background-color: tomato;
       }