CSS 中的单位(1)

192 阅读3分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

在CSS单位的世界里,主要有两大阵营,相对单位绝对单位,在相对单位中包括比如 EM、REM、VW VH 或者百分比,所有这些我们都用来定义一些相对于另一个值的长度或大小,而绝对单位,比如像素(px)和厘米(cm),CH(英寸),MM(毫米),甚至还有四分之一毫米,这些都不太常用,绝对单位组的大小总是相对固定,所以我将更关注相对单位。

绝对单位

在这些绝对单位中最常见的是 px 也就是像素,还有许多其他的绝对单位,有厘米,毫米,四分之一毫米,英寸等。

有一点我们需要注意,以像素为例,一个像素不一定是你屏幕上的一个像素,在过去的标准化的显示器和分辨率都相当差,但现在我们有高分辨率的显示器,如视网膜显示器,所以过去的一个像素的空间现在可以放是两个或更多像素。

    <section>
        <h1>Machine learning</h1>
        <h3>Machine learning</h3>
    </section>
h1{
    font-size: 96px;
}
h3{
    font-size: 1in;
}

003.png

相对单位

我们的重点还是相对单位,以百分比开始,这里百分比总是相对于一个值,例如父级元素的宽度。

屏幕快照 2021-10-08 下午1.16.20.png

比如说我有两张图片,我想让这两张图片并排在一起,占据父容器的 50% 的空间。用一个百分比来设置每张图片的宽度为50%,也就是父图片宽度的 50%

#gallery{
    width: 1000px;
    border: 1px solid darkorange;
}
img{
    width: 49.6%;
}
  • widt:50% 通常是父级元素宽度的一半
  • line-height:50% 通常是 font-size 一半

如果你把line-height(行高)设置为 50%,并不是说是父元素的 line-height(行高)的 50%,而是说元素本身的 font-size(字体大小)的 50%,所以百分比的工作方式确实不同,意思是每一次都只是其他数值的一个百分比,但其他数值是什么会有不同,可以通过阅读文档,来了解下 % 是其他某一个值的百分比。

h1.title{
    font-size: 96px;
    line-height: 50%;
    background: lemonchiffon;
}

006.png

EM

默认情况下 EM = 16px,如果 EM 可以找到距离其最近的 font-size 指定大小,就会根据该大小来调整 EM 的大小,也就是 1 EM 等于 font-size 的大小。

<div class="container">
    <div class="box_1"></div>
    <div class="box_2"></div>
</div>
.container{
    height: 200px;
    width: 200px;
    font-size: 20px;
    background-color: lightcoral;
    /* border: 3px solid orangered; */
}

.container .box_1, .container .box_2{
    font-size: 10px;
    background-color: aquamarine;
    height: 10em;
    width: 10em;
    border: 1px solid darkblue;
}

001.png

  • 这里 box_1 的 em 一个单位大小会参照与该 div 父级元素中设定 font-size 大小,也就是 em = 20px 那么 10em 也就是 100px。
<div class="container-2">
    <div class="box_b">
        <div class="box_m">
            <div class="box_s"></div>
        </div>
    </div>
</div>
.container-2{
    background-color: aquamarine;
    font-size: 20px;
    height: 20em;
    width: 20em;
}

.container-2 .box_b{
    background-color:blueviolet;
    height: 15em;
    width: 15em;
}

.container-2 .box_m{
    background-color:tomato;
    height: 10em;
    width: 10em;
}

.container-2 .box_s{
    background-color:blueviolet;
    height: 5em;
    width: 5em;
}

002.png

REM

REM 也是一个相对单位,从名字上来看相对之前介绍 EM 多了个 R,这个 R 其实 Root 缩写,这里 root{} 选择器。在 html 中可以 html{} 选择器代替 root{} 选择器。

<section class="container-3">
    <div class="box1">字体大小</div>
    <div class="box2">字体大小</div>
    <div class="box3">字体大小</div>
</section>
.container-3 .box1{
    font-size: 16px;
}

.container-3 .box2{
    font-size: 1rem;
}

007.png

这里分别给 box1 和 box2 分别指定了 font-size 为 16px 和 1rem 因为默认根的 font-size:16px

html{
    font-size: 32px;
}

当把 html 中的 font-size:32px,就变成下面这样。

008.png